2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include <folly/Executor.h>
19 #include <folly/experimental/wangle/concurrent/LifoSemMPMCQueue.h>
20 #include <folly/experimental/wangle/concurrent/NamedThreadFactory.h>
21 #include <folly/experimental/wangle/rx/Observable.h>
22 #include <folly/Baton.h>
23 #include <folly/Memory.h>
24 #include <folly/RWSpinLock.h>
30 #include <glog/logging.h>
32 namespace folly { namespace wangle {
34 class ThreadPoolExecutor : public Executor {
36 explicit ThreadPoolExecutor(
38 std::shared_ptr<ThreadFactory> threadFactory);
40 ~ThreadPoolExecutor();
42 virtual void add(Func func) override = 0;
45 std::chrono::milliseconds expiration,
46 Func expireCallback) = 0;
48 void setThreadFactory(std::shared_ptr<ThreadFactory> threadFactory) {
49 CHECK(numThreads() == 0);
50 threadFactory_ = std::move(threadFactory);
53 std::shared_ptr<ThreadFactory> getThreadFactory(void) {
54 return threadFactory_;
58 void setNumThreads(size_t numThreads);
60 * stop() is best effort - there is no guarantee that unexecuted tasks won't
61 * be executed before it returns. Specifically, IOThreadPoolExecutor's stop()
62 * behaves like join().
68 PoolStats() : threadCount(0), idleThreadCount(0), activeThreadCount(0),
69 pendingTaskCount(0), totalTaskCount(0) {}
70 size_t threadCount, idleThreadCount, activeThreadCount;
71 uint64_t pendingTaskCount, totalTaskCount;
74 PoolStats getPoolStats();
77 TaskStats() : expired(false), waitTime(0), runTime(0) {}
79 std::chrono::nanoseconds waitTime;
80 std::chrono::nanoseconds runTime;
83 Subscription<TaskStats> subscribeToTaskStats(
84 const ObserverPtr<TaskStats>& observer) {
85 return taskStatsSubject_->subscribe(observer);
89 // Prerequisite: threadListLock_ writelocked
90 void addThreads(size_t n);
91 // Prerequisite: threadListLock_ writelocked
92 void removeThreads(size_t n, bool isJoin);
94 struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING Thread {
95 explicit Thread(ThreadPoolExecutor* pool)
99 taskStatsSubject(pool->taskStatsSubject_) {}
103 static std::atomic<uint64_t> nextId;
107 Baton<> startupBaton;
108 std::shared_ptr<Subject<TaskStats>> taskStatsSubject;
111 typedef std::shared_ptr<Thread> ThreadPtr;
116 std::chrono::milliseconds expiration,
117 Func&& expireCallback);
120 std::chrono::steady_clock::time_point enqueueTime_;
121 std::chrono::milliseconds expiration_;
122 Func expireCallback_;
125 static void runTask(const ThreadPtr& thread, Task&& task);
127 // The function that will be bound to pool threads. It must call
128 // thread->startupBaton.post() when it's ready to consume work.
129 virtual void threadRun(ThreadPtr thread) = 0;
131 // Stop n threads and put their ThreadPtrs in the threadsStopped_ queue
132 // Prerequisite: threadListLock_ writelocked
133 virtual void stopThreads(size_t n) = 0;
135 // Create a suitable Thread struct
136 virtual ThreadPtr makeThread() {
137 return std::make_shared<Thread>(this);
140 // Prerequisite: threadListLock_ readlocked
141 virtual uint64_t getPendingTaskCount() = 0;
145 void add(const ThreadPtr& state) {
146 auto it = std::lower_bound(vec_.begin(), vec_.end(), state, compare);
147 vec_.insert(it, state);
150 void remove(const ThreadPtr& state) {
151 auto itPair = std::equal_range(vec_.begin(), vec_.end(), state, compare);
152 CHECK(itPair.first != vec_.end());
153 CHECK(std::next(itPair.first) == itPair.second);
154 vec_.erase(itPair.first);
157 const std::vector<ThreadPtr>& get() const {
162 static bool compare(const ThreadPtr& ts1, const ThreadPtr& ts2) {
163 return ts1->id < ts2->id;
166 std::vector<ThreadPtr> vec_;
169 class StoppedThreadQueue : public BlockingQueue<ThreadPtr> {
171 void add(ThreadPtr item) override;
172 ThreadPtr take() override;
173 size_t size() override;
178 std::queue<ThreadPtr> queue_;
181 std::shared_ptr<ThreadFactory> threadFactory_;
182 ThreadList threadList_;
183 RWSpinLock threadListLock_;
184 StoppedThreadQueue stoppedThreads_;
185 std::atomic<bool> isJoin_; // whether the current downsizing is a join
187 std::shared_ptr<Subject<TaskStats>> taskStatsSubject_;