451f164f54497d2f528a3e7b45b3f84269b0398b
[folly.git] / folly / experimental / wangle / concurrent / ThreadPoolExecutor.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
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>
25
26 #include <algorithm>
27 #include <mutex>
28 #include <queue>
29
30 #include <glog/logging.h>
31
32 namespace folly { namespace wangle {
33
34 class ThreadPoolExecutor : public Executor {
35  public:
36   explicit ThreadPoolExecutor(
37       size_t numThreads,
38       std::shared_ptr<ThreadFactory> threadFactory);
39
40   ~ThreadPoolExecutor();
41
42   virtual void add(Func func) override = 0;
43   virtual void add(
44       Func func,
45       std::chrono::milliseconds expiration,
46       Func expireCallback) = 0;
47
48   void setThreadFactory(std::shared_ptr<ThreadFactory> threadFactory) {
49     CHECK(numThreads() == 0);
50     threadFactory_ = std::move(threadFactory);
51   }
52
53   std::shared_ptr<ThreadFactory> getThreadFactory(void) {
54     return threadFactory_;
55   }
56
57   size_t numThreads();
58   void setNumThreads(size_t numThreads);
59   /*
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().
63    */
64   void stop();
65   void join();
66
67   struct PoolStats {
68     PoolStats() : threadCount(0), idleThreadCount(0), activeThreadCount(0),
69                   pendingTaskCount(0), totalTaskCount(0) {}
70     size_t threadCount, idleThreadCount, activeThreadCount;
71     uint64_t pendingTaskCount, totalTaskCount;
72   };
73
74   PoolStats getPoolStats();
75
76   struct TaskStats {
77     TaskStats() : expired(false), waitTime(0), runTime(0) {}
78     bool expired;
79     std::chrono::nanoseconds waitTime;
80     std::chrono::nanoseconds runTime;
81   };
82
83   Subscription<TaskStats> subscribeToTaskStats(
84       const ObserverPtr<TaskStats>& observer) {
85     return taskStatsSubject_->subscribe(observer);
86   }
87
88  protected:
89   // Prerequisite: threadListLock_ writelocked
90   void addThreads(size_t n);
91   // Prerequisite: threadListLock_ writelocked
92   void removeThreads(size_t n, bool isJoin);
93
94   struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING Thread {
95     explicit Thread(ThreadPoolExecutor* pool)
96       : id(nextId++),
97         handle(),
98         idle(true),
99         taskStatsSubject(pool->taskStatsSubject_) {}
100
101     virtual ~Thread() {}
102
103     static std::atomic<uint64_t> nextId;
104     uint64_t id;
105     std::thread handle;
106     bool idle;
107     Baton<> startupBaton;
108     std::shared_ptr<Subject<TaskStats>> taskStatsSubject;
109   };
110
111   typedef std::shared_ptr<Thread> ThreadPtr;
112
113   struct Task {
114     explicit Task(
115         Func&& func,
116         std::chrono::milliseconds expiration,
117         Func&& expireCallback);
118     Func func_;
119     TaskStats stats_;
120     std::chrono::steady_clock::time_point enqueueTime_;
121     std::chrono::milliseconds expiration_;
122     Func expireCallback_;
123   };
124
125   static void runTask(const ThreadPtr& thread, Task&& task);
126
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;
130
131   // Stop n threads and put their ThreadPtrs in the threadsStopped_ queue
132   // Prerequisite: threadListLock_ writelocked
133   virtual void stopThreads(size_t n) = 0;
134
135   // Create a suitable Thread struct
136   virtual ThreadPtr makeThread() {
137     return std::make_shared<Thread>(this);
138   }
139
140   // Prerequisite: threadListLock_ readlocked
141   virtual uint64_t getPendingTaskCount() = 0;
142
143   class ThreadList {
144    public:
145     void add(const ThreadPtr& state) {
146       auto it = std::lower_bound(vec_.begin(), vec_.end(), state, compare);
147       vec_.insert(it, state);
148     }
149
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);
155     }
156
157     const std::vector<ThreadPtr>& get() const {
158       return vec_;
159     }
160
161    private:
162     static bool compare(const ThreadPtr& ts1, const ThreadPtr& ts2) {
163       return ts1->id < ts2->id;
164     }
165
166     std::vector<ThreadPtr> vec_;
167   };
168
169   class StoppedThreadQueue : public BlockingQueue<ThreadPtr> {
170    public:
171     void add(ThreadPtr item) override;
172     ThreadPtr take() override;
173     size_t size() override;
174
175    private:
176     LifoSem sem_;
177     std::mutex mutex_;
178     std::queue<ThreadPtr> queue_;
179   };
180
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
186
187   std::shared_ptr<Subject<TaskStats>> taskStatsSubject_;
188 };
189
190 }} // folly::wangle