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