2 * Copyright 2014 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/experimental/wangle/concurrent/ThreadPoolExecutor.h>
21 namespace folly { namespace wangle {
23 class CPUThreadPoolExecutor : public ThreadPoolExecutor {
27 explicit 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);
35 explicit CPUThreadPoolExecutor(
37 std::shared_ptr<ThreadFactory> threadFactory);
39 explicit CPUThreadPoolExecutor(
41 uint32_t numPriorities,
42 std::shared_ptr<ThreadFactory> threadFactory =
43 std::make_shared<NamedThreadFactory>("CPUThreadPool"));
45 ~CPUThreadPoolExecutor();
47 void add(Func func) override;
50 std::chrono::milliseconds expiration,
51 Func expireCallback = nullptr) override;
53 void add(Func func, uint32_t priority);
57 std::chrono::milliseconds expiration,
58 Func expireCallback = nullptr);
60 uint32_t getNumPriorities() const;
62 struct CPUTask : public ThreadPoolExecutor::Task {
63 // Must be noexcept move constructible so it can be used in MPMCQueue
66 std::chrono::milliseconds expiration,
67 Func&& expireCallback)
68 : Task(std::move(f), expiration, std::move(expireCallback)),
71 : Task(nullptr, std::chrono::milliseconds(0), nullptr),
73 CPUTask(CPUTask&& o) noexcept : Task(std::move(o)), poison(o.poison) {}
74 CPUTask(const CPUTask&) = default;
75 CPUTask& operator=(const CPUTask&) = default;
79 static const size_t kDefaultMaxQueueSize;
80 static const size_t kDefaultNumPriorities;
83 BlockingQueue<CPUTask>* getTaskQueue();
86 void threadRun(ThreadPtr thread) override;
87 void stopThreads(size_t n) override;
88 uint64_t getPendingTaskCount() override;
90 std::unique_ptr<BlockingQueue<CPUTask>> taskQueue_;
91 std::atomic<ssize_t> threadsToStop_{0};