forked from cppalliance/capy
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththread_pool.cpp
More file actions
332 lines (290 loc) · 8.19 KB
/
thread_pool.cpp
File metadata and controls
332 lines (290 loc) · 8.19 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
// Copyright (c) 2026 Michael Vandeberg
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/capy
//
#include <boost/capy/ex/thread_pool.hpp>
#include <boost/capy/continuation.hpp>
#include <boost/capy/detail/thread_local_ptr.hpp>
#include <boost/capy/ex/frame_allocator.hpp>
#include <boost/capy/test/thread_name.hpp>
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <thread>
#include <vector>
/*
Thread pool implementation using a shared work queue.
Work items are continuations linked via their intrusive next pointer,
stored in a single queue protected by a mutex. No per-post heap
allocation: the continuation is owned by the caller and linked
directly. Worker threads wait on a condition_variable until work
is available or stop is requested.
Threads are started lazily on first post() via std::call_once to avoid
spawning threads for pools that are constructed but never used. Each
thread is named with a configurable prefix plus index for debugger
visibility.
Work tracking: on_work_started/on_work_finished maintain an atomic
outstanding_work_ counter. join() blocks until this counter reaches
zero, then signals workers to stop and joins threads.
Two shutdown paths:
- join(): waits for outstanding work to drain, then stops workers.
- stop(): immediately signals workers to exit; queued work is abandoned.
- Destructor: stop() then join() (abandon + wait for threads).
*/
namespace boost {
namespace capy {
//------------------------------------------------------------------------------
class thread_pool::impl
{
// Identifies the pool owning the current worker thread, or
// nullptr if the calling thread is not a pool worker. Checked
// by dispatch() to decide between symmetric transfer (inline
// resume) and post.
static inline detail::thread_local_ptr<impl const> current_;
// Intrusive queue of continuations via continuation::next.
// No per-post allocation: the continuation is owned by the caller.
continuation* head_ = nullptr;
continuation* tail_ = nullptr;
void push(continuation* c) noexcept
{
c->next = nullptr;
if(tail_)
tail_->next = c;
else
head_ = c;
tail_ = c;
}
continuation* pop() noexcept
{
if(!head_)
return nullptr;
continuation* c = head_;
head_ = head_->next;
if(!head_)
tail_ = nullptr;
return c;
}
bool empty() const noexcept
{
return head_ == nullptr;
}
std::mutex mutex_;
std::condition_variable work_cv_;
std::condition_variable done_cv_;
std::vector<std::thread> threads_;
std::atomic<std::size_t> outstanding_work_{0};
bool stop_{false};
bool joined_{false};
std::size_t num_threads_;
char thread_name_prefix_[13]{}; // 12 chars max + null terminator
std::once_flag start_flag_;
public:
~impl() = default;
bool
running_in_this_thread() const noexcept
{
return current_.get() == this;
}
// Destroy abandoned coroutine frames. Must be called
// before execution_context::shutdown()/destroy() so
// that suspended-frame destructors (e.g. delay_awaitable
// calling timer_service::cancel()) run while services
// are still valid.
void
drain_abandoned() noexcept
{
while(auto* c = pop())
{
auto h = c->h;
if(h && h != std::noop_coroutine())
h.destroy();
}
}
impl(std::size_t num_threads, std::string_view thread_name_prefix)
: num_threads_(num_threads)
{
if(num_threads_ == 0)
num_threads_ = std::max(
std::thread::hardware_concurrency(), 1u);
// Truncate prefix to 12 chars, leaving room for up to 3-digit index.
auto n = thread_name_prefix.copy(thread_name_prefix_, 12);
thread_name_prefix_[n] = '\0';
}
void
post(continuation& c)
{
ensure_started();
{
std::lock_guard<std::mutex> lock(mutex_);
push(&c);
}
work_cv_.notify_one();
}
void
on_work_started() noexcept
{
outstanding_work_.fetch_add(1, std::memory_order_acq_rel);
}
void
on_work_finished() noexcept
{
if(outstanding_work_.fetch_sub(
1, std::memory_order_acq_rel) == 1)
{
std::lock_guard<std::mutex> lock(mutex_);
if(joined_ && !stop_)
stop_ = true;
done_cv_.notify_all();
work_cv_.notify_all();
}
}
void
join() noexcept
{
{
std::unique_lock<std::mutex> lock(mutex_);
if(joined_)
return;
joined_ = true;
if(outstanding_work_.load(
std::memory_order_acquire) == 0)
{
stop_ = true;
work_cv_.notify_all();
}
else
{
done_cv_.wait(lock, [this]{
return stop_;
});
}
}
for(auto& t : threads_)
if(t.joinable())
t.join();
}
void
stop() noexcept
{
{
std::lock_guard<std::mutex> lock(mutex_);
stop_ = true;
}
work_cv_.notify_all();
done_cv_.notify_all();
}
private:
void
ensure_started()
{
std::call_once(start_flag_, [this]{
threads_.reserve(num_threads_);
for(std::size_t i = 0; i < num_threads_; ++i)
threads_.emplace_back([this, i]{ run(i); });
});
}
void
run(std::size_t index)
{
// Build name; set_current_thread_name truncates to platform limits.
char name[16];
std::snprintf(name, sizeof(name), "%s%zu", thread_name_prefix_, index);
set_current_thread_name(name);
// Mark this thread as a worker of this pool so dispatch()
// can symmetric-transfer when called from within pool work.
struct scoped_pool
{
scoped_pool(impl const* p) noexcept { current_.set(p); }
~scoped_pool() noexcept { current_.set(nullptr); }
} guard(this);
for(;;)
{
continuation* c = nullptr;
{
std::unique_lock<std::mutex> lock(mutex_);
work_cv_.wait(lock, [this]{
return !empty() ||
stop_;
});
if(stop_)
return;
c = pop();
}
if(c)
safe_resume(c->h);
}
}
};
//------------------------------------------------------------------------------
thread_pool::
~thread_pool()
{
impl_->stop();
impl_->join();
impl_->drain_abandoned();
shutdown();
destroy();
delete impl_;
}
thread_pool::
thread_pool(std::size_t num_threads, std::string_view thread_name_prefix)
: impl_(new impl(num_threads, thread_name_prefix))
{
this->set_frame_allocator(std::allocator<void>{});
}
void
thread_pool::
join() noexcept
{
impl_->join();
}
void
thread_pool::
stop() noexcept
{
impl_->stop();
}
//------------------------------------------------------------------------------
thread_pool::executor_type
thread_pool::
get_executor() const noexcept
{
return executor_type(
const_cast<thread_pool&>(*this));
}
void
thread_pool::executor_type::
on_work_started() const noexcept
{
pool_->impl_->on_work_started();
}
void
thread_pool::executor_type::
on_work_finished() const noexcept
{
pool_->impl_->on_work_finished();
}
void
thread_pool::executor_type::
post(continuation& c) const
{
pool_->impl_->post(c);
}
std::coroutine_handle<>
thread_pool::executor_type::
dispatch(continuation& c) const
{
if(pool_->impl_->running_in_this_thread())
return c.h;
pool_->impl_->post(c);
return std::noop_coroutine();
}
} // capy
} // boost