ThreadPoolExecutor and its children CPUThreadPoolExecutor and IOThreadPoolExecutor
[folly.git] / folly / experimental / wangle / concurrent / CPUThreadPoolExecutor.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
20 namespace folly { namespace wangle {
21
22 class CPUThreadPoolExecutor : public ThreadPoolExecutor {
23  public:
24   struct Task;
25
26   // TODO thread naming, perhaps a required input to ThreadFactories
27   explicit CPUThreadPoolExecutor(
28       size_t numThreads,
29       std::unique_ptr<BlockingQueue<Task>> taskQueue =
30           folly::make_unique<LifoSemMPMCQueue<Task>>(
31               CPUThreadPoolExecutor::kDefaultMaxQueueSize),
32       std::unique_ptr<ThreadFactory> threadFactory =
33           folly::make_unique<NamedThreadFactory>("CPUThreadPool"));
34
35   ~CPUThreadPoolExecutor();
36
37   void add(Func func) override;
38
39   struct Task {
40     explicit Task(Func&& taskArg) : func(std::move(taskArg)), poison(false) {}
41     Task() : func(nullptr), poison(true) {}
42     Task(Task&& o) noexcept : func(std::move(o.func)), poison(o.poison) {}
43     Task(const Task&) = default;
44     Task& operator=(const Task&) = default;
45     Func func;
46     bool poison;
47     // TODO per-task stats, timeouts, expirations
48   };
49
50   static const size_t kDefaultMaxQueueSize;
51
52  private:
53   void threadRun(ThreadPtr thread) override;
54   void stopThreads(size_t n) override;
55
56   std::atomic<size_t> threadsToStop_;
57   std::unique_ptr<BlockingQueue<Task>> taskQueue_;
58 };
59
60 }} // folly::wangle