Kill get_fast/get_weak_fast Singletonn API
[folly.git] / folly / 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/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>
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 virtual 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   /**
89    * Base class for threads created with ThreadPoolExecutor.
90    * Some subclasses have methods that operate on these
91    * handles.
92    */
93   class ThreadHandle {
94    public:
95     virtual ~ThreadHandle() = default;
96   };
97
98   /**
99    * Observer interface for thread start/stop.
100    * Provides hooks so actions can be taken when
101    * threads are created
102    */
103   class Observer {
104    public:
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;
110   };
111
112   void addObserver(std::shared_ptr<Observer>);
113   void removeObserver(std::shared_ptr<Observer>);
114
115  protected:
116   // Prerequisite: threadListLock_ writelocked
117   void addThreads(size_t n);
118   // Prerequisite: threadListLock_ writelocked
119   void removeThreads(size_t n, bool isJoin);
120
121   struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING Thread : public ThreadHandle {
122     explicit Thread(ThreadPoolExecutor* pool)
123       : id(nextId++),
124         handle(),
125         idle(true),
126         taskStatsSubject(pool->taskStatsSubject_) {}
127
128     virtual ~Thread() {}
129
130     static std::atomic<uint64_t> nextId;
131     uint64_t id;
132     std::thread handle;
133     bool idle;
134     Baton<> startupBaton;
135     std::shared_ptr<Subject<TaskStats>> taskStatsSubject;
136   };
137
138   typedef std::shared_ptr<Thread> ThreadPtr;
139
140   struct Task {
141     explicit Task(
142         Func&& func,
143         std::chrono::milliseconds expiration,
144         Func&& expireCallback);
145     Func func_;
146     TaskStats stats_;
147     std::chrono::steady_clock::time_point enqueueTime_;
148     std::chrono::milliseconds expiration_;
149     Func expireCallback_;
150   };
151
152   static void runTask(const ThreadPtr& thread, Task&& task);
153
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;
157
158   // Stop n threads and put their ThreadPtrs in the threadsStopped_ queue
159   // Prerequisite: threadListLock_ writelocked
160   virtual void stopThreads(size_t n) = 0;
161
162   // Create a suitable Thread struct
163   virtual ThreadPtr makeThread() {
164     return std::make_shared<Thread>(this);
165   }
166
167   // Prerequisite: threadListLock_ readlocked
168   virtual uint64_t getPendingTaskCount() = 0;
169
170   class ThreadList {
171    public:
172     void add(const ThreadPtr& state) {
173       auto it = std::lower_bound(vec_.begin(), vec_.end(), state, compare);
174       vec_.insert(it, state);
175     }
176
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);
182     }
183
184     const std::vector<ThreadPtr>& get() const {
185       return vec_;
186     }
187
188    private:
189     static bool compare(const ThreadPtr& ts1, const ThreadPtr& ts2) {
190       return ts1->id < ts2->id;
191     }
192
193     std::vector<ThreadPtr> vec_;
194   };
195
196   class StoppedThreadQueue : public BlockingQueue<ThreadPtr> {
197    public:
198     void add(ThreadPtr item) override;
199     ThreadPtr take() override;
200     size_t size() override;
201
202    private:
203     LifoSem sem_;
204     std::mutex mutex_;
205     std::queue<ThreadPtr> queue_;
206   };
207
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
213
214   std::shared_ptr<Subject<TaskStats>> taskStatsSubject_;
215   std::vector<std::shared_ptr<Observer>> observers_;
216 };
217
218 }} // folly::wangle