Action Engine
Loading...
Searching...
No Matches
thread_pool.h
1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef THREAD_FIBER_THREAD_POOL_H_
16#define THREAD_FIBER_THREAD_POOL_H_
17
18#include <atomic>
19#include <thread>
20
21#include <boost/context/pooled_fixedsize_stack.hpp>
22#include <boost/context/posix/protected_fixedsize_stack.hpp>
23
24#include "thread/boost_primitives.h"
25
26namespace thread {
27template <typename Algo, typename... Args>
28static void EnsureThreadHasScheduler(Args&&... args) {
29 thread_local bool kThreadHasScheduler = false;
30 if (kThreadHasScheduler) {
31 return;
32 }
33
34 boost::fibers::use_scheduling_algorithm<Algo>(std::forward<Args>(args)...);
35 kThreadHasScheduler = true;
36}
37
38class WorkerThreadPool {
39 public:
40 explicit WorkerThreadPool() = default;
41
42 void Start(size_t num_threads = std::thread::hardware_concurrency());
43
44 void Schedule(boost::fibers::context* ctx);
45
46 static WorkerThreadPool& Instance();
47
48 boost::context::protected_fixedsize_stack& Allocator() { return alloc; }
49
50 private:
51 struct Worker {
52 std::thread thread;
53 };
54
55 static constexpr bool kScheduleOnSelf = true;
56
57 boost::context::protected_fixedsize_stack alloc;
58
59 act::concurrency::impl::Mutex mu_{};
60 std::atomic<size_t> worker_idx_{0};
61 absl::InlinedVector<Worker, 16> workers_{};
62 absl::InlinedVector<boost::fibers::scheduler*, 16> schedulers_{};
63};
64
65void EnsureWorkerThreadPool();
66} // namespace thread
67
68#endif // THREAD_FIBER_THREAD_POOL_H_