-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread-pool.hpp
More file actions
231 lines (195 loc) · 6.01 KB
/
thread-pool.hpp
File metadata and controls
231 lines (195 loc) · 6.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#pragma once
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include <type_traits>
#include <atomic>
class ThreadPool {
public:
explicit ThreadPool(std::size_t thread_count = std::thread::hardware_concurrency())
: stop(false), paused(false), active_tasks_(0)
{
if (thread_count == 0) thread_count = 1;
spawn_workers(thread_count);
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
ThreadPool(ThreadPool&&) = delete;
ThreadPool& operator=(ThreadPool&&) = delete;
~ThreadPool() { shutdown(); }
/**
* Adds a new task to the thread pool.
* The task is defined by a callable `f` and its arguments `args`.
*/
template<typename F, typename... Args>
auto submit_task(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>>
{
using ReturnType = std::invoke_result_t<F, Args...>;
{
std::unique_lock<std::mutex> lock(m);
if (stop) throw std::runtime_error("ThreadPool: submit on stopped pool");
}
auto task = std::make_shared<std::packaged_task<ReturnType()>>(
[f = std::forward<F>(f),
args_tuple = std::make_tuple(std::forward<Args>(args)...)]() mutable {
return std::apply(std::move(f), std::move(args_tuple));
}
);
std::future<ReturnType> future = task->get_future();
{
std::unique_lock<std::mutex> lock(m);
tasks.emplace([task]() { (*task)(); });
}
cv_task.notify_one(); // Notify one worker that a new task is available
return future;
}
/**
* Waits for all currently queued and active tasks to complete.
*/
void wait_all()
{
std::unique_lock<std::mutex> lock(m);
cv_done.wait(lock, [this] {
return tasks.empty() && active_tasks_ == 0;
});
}
/**
* Checks if there are no pending tasks and no active tasks in the thread pool.
*/
[[nodiscard]] bool all_done() const
{
std::unique_lock<std::mutex> lock(m);
return tasks.empty() && active_tasks_ == 0;
}
/**
* Pauses the thread pool, preventing workers from executing tasks
* until `resume()` is called.
*/
void pause()
{
std::unique_lock<std::mutex> lock(m);
paused = true;
}
/**
* Resumes the thread pool, allowing workers to execute tasks again after being paused.
*/
void resume()
{
{
std::unique_lock<std::mutex> lock(m);
paused = false;
}
cv_task.notify_all();
}
[[nodiscard]] bool is_paused() const
{
std::unique_lock<std::mutex> lock(m);
return paused;
}
void resize(std::size_t new_count)
{
if (new_count == 0) new_count = 1;
std::size_t current = workers.size();
if (new_count == current) return;
if (new_count > current) {
spawn_workers(new_count - current);
} else {
{
std::unique_lock<std::mutex> lock(m);
workers_to_remove += (current - new_count);
}
cv_task.notify_all();
workers.erase(
std::remove_if(workers.begin(), workers.end(),
[](std::thread& t) {
if (t.joinable()) { t.join(); return true; }
return false;
}),
workers.end()
);
}
}
void shutdown()
{
{
std::unique_lock<std::mutex> lock(m);
if (stop) return;
stop = true;
}
cv_task.notify_all();
for (auto& w : workers) if (w.joinable()) w.join();
workers.clear();
}
void shutdown_now()
{
{
std::unique_lock<std::mutex> lock(m);
if (stop) return;
stop = true;
std::queue<std::function<void()>> empty;
std::swap(tasks, empty);
}
cv_task.notify_all();
for (auto& w : workers) if (w.joinable()) w.join();
workers.clear();
}
[[nodiscard]] std::size_t pending_tasks() const
{
std::unique_lock<std::mutex> lock(m);
return tasks.size();
}
[[nodiscard]] std::size_t active_tasks() const
{
return active_tasks_.load(std::memory_order_relaxed);
}
[[nodiscard]] std::size_t thread_count() const
{
std::unique_lock<std::mutex> lock(m);
return workers.size();
}
private:
void spawn_workers(std::size_t n)
{
for (std::size_t i = 0; i < n; ++i)
workers.emplace_back([this] { worker_loop(); });
}
void worker_loop()
{
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(m);
cv_task.wait(lock, [this] {
return stop || workers_to_remove > 0 || (!paused && !tasks.empty());
});
if (stop && tasks.empty()) return;
if (workers_to_remove > 0) { --workers_to_remove; return; }
if (paused) continue;
task = std::move(tasks.front());
tasks.pop();
}
++active_tasks_;
try { task(); } catch (...) {}
--active_tasks_;
{
std::unique_lock<std::mutex> lock(m);
if (tasks.empty() && active_tasks_ == 0)
cv_done.notify_all();
}
}
}
mutable std::mutex m;
std::condition_variable cv_task;
std::condition_variable cv_done;
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
bool stop;
bool paused;
std::size_t workers_to_remove = 0;
std::atomic<std::size_t> active_tasks_;
};