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/wangle/concurrent/LifoSemMPMCQueue.h>
20 #include <folly/wangle/concurrent/NamedThreadFactory.h>
21 #include <folly/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 virtual 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 * Base class for threads created with ThreadPoolExecutor.
90 * Some subclasses have methods that operate on these
95 virtual ~ThreadHandle() = default;
99 * Observer interface for thread start/stop.
100 * Provides hooks so actions can be taken when
101 * threads are created
105 virtual void threadStarted(ThreadHandle*) = 0;
106 virtual void threadStopped(ThreadHandle*) = 0;
107 virtual void threadPreviouslyStarted(ThreadHandle*) = 0;
108 virtual void threadNotYetStopped(ThreadHandle*) = 0;
109 virtual ~Observer() = default;
112 void addObserver(std::shared_ptr<Observer>);
113 void removeObserver(std::shared_ptr<Observer>);
116 // Prerequisite: threadListLock_ writelocked
117 void addThreads(size_t n);
118 // Prerequisite: threadListLock_ writelocked
119 void removeThreads(size_t n, bool isJoin);
121 struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING Thread : public ThreadHandle {
122 explicit Thread(ThreadPoolExecutor* pool)
126 taskStatsSubject(pool->taskStatsSubject_) {}
130 static std::atomic<uint64_t> nextId;
134 Baton<> startupBaton;
135 std::shared_ptr<Subject<TaskStats>> taskStatsSubject;
138 typedef std::shared_ptr<Thread> ThreadPtr;
143 std::chrono::milliseconds expiration,
144 Func&& expireCallback);
147 std::chrono::steady_clock::time_point enqueueTime_;
148 std::chrono::milliseconds expiration_;
149 Func expireCallback_;
152 static void runTask(const ThreadPtr& thread, Task&& task);
154 // The function that will be bound to pool threads. It must call
155 // thread->startupBaton.post() when it's ready to consume work.
156 virtual void threadRun(ThreadPtr thread) = 0;
158 // Stop n threads and put their ThreadPtrs in the threadsStopped_ queue
159 // Prerequisite: threadListLock_ writelocked
160 virtual void stopThreads(size_t n) = 0;
162 // Create a suitable Thread struct
163 virtual ThreadPtr makeThread() {
164 return std::make_shared<Thread>(this);
167 // Prerequisite: threadListLock_ readlocked
168 virtual uint64_t getPendingTaskCount() = 0;
172 void add(const ThreadPtr& state) {
173 auto it = std::lower_bound(vec_.begin(), vec_.end(), state, compare);
174 vec_.insert(it, state);
177 void remove(const ThreadPtr& state) {
178 auto itPair = std::equal_range(vec_.begin(), vec_.end(), state, compare);
179 CHECK(itPair.first != vec_.end());
180 CHECK(std::next(itPair.first) == itPair.second);
181 vec_.erase(itPair.first);
184 const std::vector<ThreadPtr>& get() const {
189 static bool compare(const ThreadPtr& ts1, const ThreadPtr& ts2) {
190 return ts1->id < ts2->id;
193 std::vector<ThreadPtr> vec_;
196 class StoppedThreadQueue : public BlockingQueue<ThreadPtr> {
198 void add(ThreadPtr item) override;
199 ThreadPtr take() override;
200 size_t size() override;
205 std::queue<ThreadPtr> queue_;
208 std::shared_ptr<ThreadFactory> threadFactory_;
209 ThreadList threadList_;
210 RWSpinLock threadListLock_;
211 StoppedThreadQueue stoppedThreads_;
212 std::atomic<bool> isJoin_; // whether the current downsizing is a join
214 std::shared_ptr<Subject<TaskStats>> taskStatsSubject_;
215 std::vector<std::shared_ptr<Observer>> observers_;