add consumeUntilDrained API to NotificationQueue::Consumer
[folly.git] / folly / experimental / wangle / concurrent / IOThreadPoolExecutor.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/experimental/wangle/concurrent/ThreadPoolExecutor.h>
19 #include <folly/io/async/EventBase.h>
20
21 namespace folly { namespace wangle {
22
23 // N.B. For this thread pool, stop() behaves like join() because outstanding
24 // tasks belong to the event base and will be executed upon its destruction.
25 class IOThreadPoolExecutor : public ThreadPoolExecutor {
26  public:
27   explicit IOThreadPoolExecutor(
28       size_t numThreads,
29       std::shared_ptr<ThreadFactory> threadFactory =
30           std::make_shared<NamedThreadFactory>("IOThreadPool"));
31
32   ~IOThreadPoolExecutor();
33
34   void add(Func func) override;
35   void add(
36       Func func,
37       std::chrono::milliseconds expiration,
38       Func expireCallback = nullptr) override;
39
40  private:
41   ThreadPtr makeThread() override;
42   void threadRun(ThreadPtr thread) override;
43   void stopThreads(size_t n) override;
44   uint64_t getPendingTaskCount() override;
45
46   struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING IOThread : public Thread {
47     IOThread(IOThreadPoolExecutor* pool)
48       : Thread(pool),
49         shouldRun(true),
50         pendingTasks(0) {};
51     std::atomic<bool> shouldRun;
52     std::atomic<size_t> pendingTasks;
53     EventBase* eventBase;
54   };
55
56   size_t nextThread_;
57 };
58
59 }} // folly::wangle