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