2 * Copyright 2017 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.
20 #include <folly/Function.h>
21 #include <folly/SharedMutex.h>
22 #include <folly/Singleton.h>
23 #include <folly/executors/IOExecutor.h>
24 #include <folly/executors/IOThreadPoolExecutor.h>
25 #include <folly/executors/InlineExecutor.h>
27 using namespace folly;
31 template <class ExecutorBase>
32 class GlobalExecutor {
34 explicit GlobalExecutor(
35 Function<std::unique_ptr<ExecutorBase>()> constructDefault)
36 : constructDefault_(std::move(constructDefault)) {}
38 std::shared_ptr<ExecutorBase> get() {
40 SharedMutex::ReadHolder guard(mutex_);
41 if (auto executor = executor_.lock()) {
42 return executor; // Fast path.
46 SharedMutex::WriteHolder guard(mutex_);
47 if (auto executor = executor_.lock()) {
51 if (!defaultExecutor_) {
52 defaultExecutor_ = constructDefault_();
55 return defaultExecutor_;
58 void set(std::weak_ptr<ExecutorBase> executor) {
59 SharedMutex::WriteHolder guard(mutex_);
60 executor_.swap(executor);
65 std::weak_ptr<ExecutorBase> executor_;
66 std::shared_ptr<ExecutorBase> defaultExecutor_;
67 Function<std::unique_ptr<ExecutorBase>()> constructDefault_;
70 Singleton<GlobalExecutor<Executor>> gGlobalCPUExecutor([] {
71 return new GlobalExecutor<Executor>(
72 // Default global CPU executor is an InlineExecutor.
73 [] { return std::make_unique<InlineExecutor>(); });
76 Singleton<GlobalExecutor<IOExecutor>> gGlobalIOExecutor([] {
77 return new GlobalExecutor<IOExecutor>(
78 // Default global IO executor is an IOThreadPoolExecutor.
80 return std::make_unique<IOThreadPoolExecutor>(
81 std::thread::hardware_concurrency(),
82 std::make_shared<NamedThreadFactory>("GlobalIOThreadPool"));
90 std::shared_ptr<Executor> getCPUExecutor() {
91 if (auto singleton = gGlobalCPUExecutor.try_get()) {
92 return singleton->get();
97 void setCPUExecutor(std::weak_ptr<Executor> executor) {
98 if (auto singleton = gGlobalCPUExecutor.try_get()) {
99 singleton->set(std::move(executor));
103 std::shared_ptr<IOExecutor> getIOExecutor() {
104 if (auto singleton = gGlobalIOExecutor.try_get()) {
105 return singleton->get();
110 void setIOExecutor(std::weak_ptr<IOExecutor> executor) {
111 if (auto singleton = gGlobalIOExecutor.try_get()) {
112 singleton->set(std::move(executor));
116 EventBase* getEventBase() {
117 return getIOExecutor()->getEventBase();