Branch data Line data Source code
1 : : // Copyright 2026 HPActor Contributors
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 : : #pragma once
16 : :
17 : : #include <hpactor/types/types.hpp>
18 : :
19 : : #include <atomic>
20 : : #include <functional>
21 : : #include <memory>
22 : : #include <mutex>
23 : : #include <thread>
24 : : #include <vector>
25 : :
26 : : namespace hpactor::sched {
27 : :
28 : : class DedicatedThreadPool {
29 : : public:
30 : : using WorkFn = std::function<void()>;
31 : :
32 : : explicit DedicatedThreadPool(uint32_t num_threads);
33 : : ~DedicatedThreadPool();
34 : :
35 : : DedicatedThreadPool(const DedicatedThreadPool&) = delete;
36 : : DedicatedThreadPool& operator=(const DedicatedThreadPool&) = delete;
37 : : DedicatedThreadPool(DedicatedThreadPool&&) = delete;
38 : : DedicatedThreadPool& operator=(DedicatedThreadPool&&) = delete;
39 : :
40 : : void start();
41 : : void stop();
42 : :
43 : : // Thread-safe: enqueue work for an actor.
44 : : // Work is distributed round-robin across pool workers.
45 : : void enqueue(ActorId actor, WorkFn work);
46 : :
47 : 3 : bool is_running() const {
48 : 3 : return running_.load(std::memory_order_acquire);
49 : : }
50 : :
51 : : size_t pending() const;
52 : :
53 : : uint32_t num_threads() const {
54 : : return num_threads_;
55 : : }
56 : :
57 : : private:
58 : : void worker_loop(uint32_t worker_id);
59 : :
60 : : struct WorkerState {
61 : : std::mutex mutex;
62 : : std::vector<WorkFn> queue;
63 : : };
64 : :
65 : : uint32_t num_threads_;
66 : : std::vector<std::thread> threads_;
67 : : std::vector<std::unique_ptr<WorkerState>> workers_;
68 : : std::atomic<bool> running_{false};
69 : : std::atomic<uint32_t> next_worker_{0};
70 : : };
71 : :
72 : : } // namespace hpactor::sched
|