TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2026 Michael Vandeberg
4 : //
5 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 : //
8 : // Official repository: https://github.com/cppalliance/capy
9 : //
10 :
11 : #ifndef BOOST_CAPY_EX_THREAD_POOL_HPP
12 : #define BOOST_CAPY_EX_THREAD_POOL_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/continuation.hpp>
16 : #include <coroutine>
17 : #include <boost/capy/ex/execution_context.hpp>
18 : #include <cstddef>
19 : #include <string_view>
20 :
21 : namespace boost {
22 : namespace capy {
23 :
24 : /** Distributes posted work across a fixed group of worker threads via a shared queue.
25 :
26 : Use this when you need to run coroutines on multiple threads
27 : without the overhead of creating and destroying threads for
28 : each task. Work items are distributed across the pool using
29 : a shared queue.
30 :
31 : @par Thread Safety
32 : Distinct objects: Safe.
33 : Shared objects: Safe for @ref get_executor, @ref join, and
34 : @ref stop. Unsafe for construction and destruction.
35 :
36 : @note `join()` waits only for work that holds outstanding-work
37 : counting, which `run_async` (and `make_work_guard`) provide. A bare
38 : `executor_type::post()` does not register outstanding work, so
39 : `join()` does not wait for it.
40 :
41 : @note A pool allocates coroutine frames with `std::allocator<void>`,
42 : not the recycling resource that is the @ref execution_context
43 : default. Call @ref execution_context::set_frame_allocator to change
44 : it.
45 :
46 : @par Example
47 : @par !example example
48 :
49 : */
50 : class BOOST_CAPY_DECL
51 : thread_pool
52 : : public execution_context
53 : {
54 : class impl;
55 : impl* impl_;
56 :
57 : public:
58 : class executor_type;
59 :
60 : /** Destroy the thread pool.
61 :
62 : Stops the pool, joins its worker threads, then abandons any
63 : work that has not started:
64 :
65 : @li Calls @ref stop. Each worker thread finishes the item it
66 : is running and exits; queued work is not run.
67 : @li Joins the worker threads. Unlike @ref join, this does not
68 : wait for outstanding work. If @ref join was already called,
69 : the threads are already joined and this step does nothing.
70 : @li Shuts down the pool's services, abandons every coroutine
71 : still queued on the pool or its strands, then destroys the
72 : services.
73 : Each abandoned chain is unwound, without delivering a
74 : result, on the executor of the coroutine that started it.
75 : That happens during this destructor when the executor is
76 : this pool, and later when it belongs to another execution
77 : context.
78 : See @ref chain_owner.
79 :
80 : To let queued work finish first, call @ref join before the
81 : pool is destroyed.
82 :
83 : @pre No thread outside this pool may post or dispatch work to it
84 : (or to a strand built on it) concurrently with, or after,
85 : destruction. Doing so is undefined behavior. Submit such work
86 : through @ref run_async and call @ref join, without calling
87 : @ref stop, before the pool is destroyed, so it has completed
88 : first. A thread owned by one of this pool's services may post
89 : or dispatch until that service's `shutdown()` returns.
90 :
91 : @pre Must not be called from a thread in this pool. A worker
92 : thread cannot join itself, so this calls `std::terminate`.
93 : */
94 : ~thread_pool();
95 :
96 : /** Construct a thread pool.
97 :
98 : Records the requested worker count; no threads are created
99 : yet. Threads start lazily on the executor's first `post()`.
100 : If `num_threads` is zero, the number of threads is set to
101 : the hardware concurrency, or one if that cannot be determined.
102 :
103 : Sets the pool's frame allocator to `std::allocator<void>`,
104 : replacing the @ref execution_context default. Call
105 : @ref execution_context::set_frame_allocator to change it.
106 :
107 : @param num_threads The number of worker threads, or zero
108 : for automatic selection.
109 :
110 : @param thread_name_prefix The prefix for worker thread names.
111 : Thread names appear as "{prefix}0", "{prefix}1", etc.
112 : The prefix is truncated to 12 characters. Defaults to
113 : "capy-pool-".
114 : */
115 : explicit
116 : thread_pool(
117 : std::size_t num_threads = 0,
118 : std::string_view thread_name_prefix = "capy-pool-");
119 :
120 : /** Copy construction is disabled; a pool owns its worker threads.
121 :
122 : @param other The pool that would be copied.
123 : */
124 : thread_pool(thread_pool const& other) = delete;
125 :
126 : /** Copy assignment is disabled; a pool owns its worker threads.
127 :
128 : @param other The pool that would be assigned from.
129 :
130 : @return A reference to `*this`.
131 : */
132 : thread_pool& operator=(thread_pool const& other) = delete;
133 :
134 : /** Wait for all outstanding work to complete.
135 :
136 : Blocks the calling thread until all outstanding work
137 : tracked by
138 : @ref executor_type::on_work_started and
139 : @ref executor_type::on_work_finished completes. After all
140 : work finishes, joins the worker threads.
141 :
142 : If @ref stop is called while `join()` is blocking, the
143 : pool stops without waiting for remaining work to
144 : complete. Worker threads finish their current item and
145 : exit; `join()` still waits for all threads to be joined
146 : before returning.
147 :
148 : Only the first call performs the join. A later call returns
149 : immediately, even while the first call is still blocking on
150 : another thread.
151 :
152 : @pre Must not be called from a thread in this pool (undefined
153 : behavior).
154 :
155 : @par Postconditions
156 : If this call performed the join, all worker threads have
157 : been joined. The pool cannot be reused.
158 :
159 : @par Thread Safety
160 : May be called from any thread not in this pool.
161 : */
162 : void
163 : join() noexcept;
164 :
165 : /** Request all worker threads to stop.
166 :
167 : Signals all threads to exit after finishing their current
168 : work item. Queued work that has not started stays queued
169 : until the pool is destroyed, which abandons it. Does not
170 : wait for threads to exit.
171 :
172 : If @ref join is blocking on another thread, calling
173 : `stop()` causes it to stop waiting for outstanding
174 : work. The `join()` call still waits for worker threads
175 : to finish their current item and exit before returning.
176 :
177 : @par Thread Safety
178 : May be called concurrently from any thread, including a
179 : thread in this pool.
180 : */
181 : void
182 : stop() noexcept;
183 :
184 : /** Return an executor for this thread pool.
185 :
186 : @return An executor associated with this thread pool.
187 : */
188 : executor_type
189 : get_executor() const noexcept;
190 : };
191 :
192 : /** Runs continuations on the worker threads of a thread_pool.
193 :
194 : Executors are lightweight handles that can be copied and stored.
195 : All copies refer to the same underlying thread pool.
196 :
197 : @par Thread Safety
198 : Distinct objects: Safe.
199 : Shared objects: Safe.
200 :
201 : @par Example
202 : @par !example example
203 : */
204 : class thread_pool::executor_type
205 : {
206 : friend class thread_pool;
207 :
208 : thread_pool* pool_ = nullptr;
209 :
210 : explicit
211 HIT 15348 : executor_type(thread_pool& pool) noexcept
212 15348 : : pool_(&pool)
213 : {
214 15348 : }
215 :
216 : public:
217 : /** Construct a default null executor.
218 :
219 : The resulting executor is not associated with any pool.
220 : `context()`, `dispatch()`, and `post()` require the
221 : executor to be associated with a pool before use.
222 : */
223 : executor_type() = default;
224 :
225 : /** Return the underlying thread pool.
226 :
227 : @return A reference to the associated pool. The behavior is
228 : undefined if the executor is not associated with a pool.
229 : */
230 : thread_pool&
231 12637 : context() const noexcept
232 : {
233 12637 : return *pool_;
234 : }
235 :
236 : /** Notify that work has started.
237 :
238 : Increments the outstanding work count. Must be paired
239 : with a subsequent call to @ref on_work_finished.
240 :
241 : @see @ref on_work_finished, @ref work_guard
242 : */
243 : BOOST_CAPY_DECL
244 : void
245 : on_work_started() const noexcept;
246 :
247 : /** Notify that work has finished.
248 :
249 : Decrements the outstanding work count. When the count
250 : reaches zero after @ref thread_pool::join is called,
251 : the pool's worker threads are signaled to stop.
252 :
253 : @pre A preceding call to @ref on_work_started was made.
254 :
255 : @see @ref on_work_started, @ref work_guard
256 : */
257 : BOOST_CAPY_DECL
258 : void
259 : on_work_finished() const noexcept;
260 :
261 : /** Dispatch a continuation for execution.
262 :
263 : If the calling thread is a worker of this pool, returns
264 : `c.h` for symmetric transfer so the caller can resume the
265 : continuation inline. Otherwise, posts the continuation as
266 : @ref post does and returns `std::noop_coroutine()`. On that
267 : path, the continuation is not run if the pool stops first,
268 : and a call that races with @ref thread_pool::stop can go
269 : either way. See @ref post.
270 :
271 : @param c The continuation to execute. On the post path,
272 : must remain at a stable address until resumed or
273 : abandoned.
274 :
275 : @return `c.h` when the calling thread is a pool worker;
276 : `std::noop_coroutine()` otherwise.
277 :
278 : @throws std::system_error If this call posts and must start
279 : the pool's worker threads, and a thread cannot be started.
280 : `c` is not queued.
281 : Threads that did start keep running, and a later call
282 : starts only the missing ones.
283 : */
284 : BOOST_CAPY_DECL
285 : std::coroutine_handle<>
286 : dispatch(continuation& c) const;
287 :
288 : /** Post a continuation to the thread pool.
289 :
290 : The continuation is resumed on one of the pool's worker
291 : threads, unless the pool stops first. The pool stops when
292 : @ref thread_pool::stop is called, or when
293 : @ref thread_pool::join has finished waiting for outstanding
294 : work. A continuation still queued when the pool stops, or
295 : posted after it stops, is not run. It stays queued until
296 : the pool is destroyed, which abandons it.
297 :
298 : A call that races with @ref thread_pool::stop on another
299 : thread can therefore go either way, and nothing in the call
300 : tells the caller which.
301 :
302 : The continuation must remain at a stable address until it
303 : is resumed or abandoned.
304 :
305 : @param c The continuation to execute.
306 :
307 : @throws std::system_error If this call must start the pool's
308 : worker threads, and a thread cannot be started. `c` is not
309 : queued.
310 : Threads that did start keep running, and a later call
311 : starts only the missing ones.
312 : */
313 : BOOST_CAPY_DECL
314 : void
315 : post(continuation& c) const;
316 :
317 : /** Return true if two executors refer to the same thread pool.
318 :
319 : @param other The executor to compare against.
320 :
321 : @return `true` if both executors refer to the same pool.
322 : */
323 : bool
324 15 : operator==(executor_type const& other) const noexcept
325 : {
326 15 : return pool_ == other.pool_;
327 : }
328 : };
329 :
330 : } // capy
331 : } // boost
332 :
333 : #endif
|