2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <folly/wangle/concurrent/ThreadPoolExecutor.h>
21 namespace folly { namespace wangle {
23 class CPUThreadPoolExecutor : public ThreadPoolExecutor {
27 CPUThreadPoolExecutor(
29 std::unique_ptr<BlockingQueue<CPUTask>> taskQueue,
30 std::shared_ptr<ThreadFactory> threadFactory =
31 std::make_shared<NamedThreadFactory>("CPUThreadPool"));
33 explicit CPUThreadPoolExecutor(size_t numThreads);
34 CPUThreadPoolExecutor(
36 std::shared_ptr<ThreadFactory> threadFactory);
38 CPUThreadPoolExecutor(
41 std::shared_ptr<ThreadFactory> threadFactory =
42 std::make_shared<NamedThreadFactory>("CPUThreadPool"));
44 CPUThreadPoolExecutor(
48 std::shared_ptr<ThreadFactory> threadFactory =
49 std::make_shared<NamedThreadFactory>("CPUThreadPool"));
51 ~CPUThreadPoolExecutor();
53 void add(Func func) override;
56 std::chrono::milliseconds expiration,
57 Func expireCallback = nullptr) override;
59 void addWithPriority(Func func, int8_t priority) override;
63 std::chrono::milliseconds expiration,
64 Func expireCallback = nullptr);
66 uint8_t getNumPriorities() const override;
68 struct CPUTask : public ThreadPoolExecutor::Task {
69 // Must be noexcept move constructible so it can be used in MPMCQueue
72 std::chrono::milliseconds expiration,
73 Func&& expireCallback)
74 : Task(std::move(f), expiration, std::move(expireCallback)),
77 : Task(nullptr, std::chrono::milliseconds(0), nullptr),
79 CPUTask(CPUTask&& o) noexcept : Task(std::move(o)), poison(o.poison) {}
80 CPUTask(const CPUTask&) = default;
81 CPUTask& operator=(const CPUTask&) = default;
85 static const size_t kDefaultMaxQueueSize;
88 BlockingQueue<CPUTask>* getTaskQueue();
91 void threadRun(ThreadPtr thread) override;
92 void stopThreads(size_t n) override;
93 uint64_t getPendingTaskCount() override;
95 std::unique_ptr<BlockingQueue<CPUTask>> taskQueue_;
96 std::atomic<ssize_t> threadsToStop_{0};