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   35  
36   @par Example 36   @par Example
37 - @code 37 + @par !example example
38 - thread_pool pool(4); // 4 worker threads 38 +
39 - auto ex = pool.get_executor();  
40 - run_async(ex)(some_task()); // start work; tracked so join() waits for it  
41 - pool.join(); // wait for outstanding work to complete  
42 - // pool destructor stops the pool, discarding any pending work  
43 - @endcode  
44   39  
45   @note `join()` waits only for work that holds outstanding-work 40   @note `join()` waits only for work that holds outstanding-work
46   counting, which `run_async` (and `make_work_guard`) provide. A bare 41   counting, which `run_async` (and `make_work_guard`) provide. A bare
47   `executor_type::post()` does not register outstanding work, so 42   `executor_type::post()` does not register outstanding work, so
48   `join()` does not wait for it. 43   `join()` does not wait for it.
49   */ 44   */
50   class BOOST_CAPY_DECL 45   class BOOST_CAPY_DECL
51   thread_pool 46   thread_pool
52   : public execution_context 47   : public execution_context
53   { 48   {
54   class impl; 49   class impl;
55   impl* impl_; 50   impl* impl_;
56   51  
57   public: 52   public:
58   class executor_type; 53   class executor_type;
59   54  
60   /** Destroy the thread pool. 55   /** Destroy the thread pool.
61   56  
62   Signals all worker threads to stop, waits for them to 57   Signals all worker threads to stop, waits for them to
63   finish, and destroys any pending work items. 58   finish, and destroys any pending work items.
64   59  
65   @pre No thread outside this pool may post or dispatch work to it 60   @pre No thread outside this pool may post or dispatch work to it
66   (or to a strand built on it) concurrently with, or after, 61   (or to a strand built on it) concurrently with, or after,
67   destruction. Doing so is undefined behavior. Submit such work 62   destruction. Doing so is undefined behavior. Submit such work
68   through @ref run_async or @ref run and call @ref join before 63   through @ref run_async or @ref run and call @ref join before
69   the pool is destroyed, so it has completed first. 64   the pool is destroyed, so it has completed first.
70   */ 65   */
71   ~thread_pool(); 66   ~thread_pool();
72   67  
73   /** Construct a thread pool. 68   /** Construct a thread pool.
74   69  
75   Records the requested worker count; no threads are created 70   Records the requested worker count; no threads are created
76   yet. Threads start lazily on the executor's first `post()`. 71   yet. Threads start lazily on the executor's first `post()`.
77   If `num_threads` is zero, the number of threads is set to 72   If `num_threads` is zero, the number of threads is set to
78   the hardware concurrency, or one if that cannot be determined. 73   the hardware concurrency, or one if that cannot be determined.
79   74  
80   @param num_threads The number of worker threads, or zero 75   @param num_threads The number of worker threads, or zero
81   for automatic selection. 76   for automatic selection.
82   77  
83   @param thread_name_prefix The prefix for worker thread names. 78   @param thread_name_prefix The prefix for worker thread names.
84   Thread names appear as "{prefix}0", "{prefix}1", etc. 79   Thread names appear as "{prefix}0", "{prefix}1", etc.
85   The prefix is truncated to 12 characters. Defaults to 80   The prefix is truncated to 12 characters. Defaults to
86   "capy-pool-". 81   "capy-pool-".
87   */ 82   */
88   explicit 83   explicit
89   thread_pool( 84   thread_pool(
90   std::size_t num_threads = 0, 85   std::size_t num_threads = 0,
91   std::string_view thread_name_prefix = "capy-pool-"); 86   std::string_view thread_name_prefix = "capy-pool-");
92   87  
93   /** Copy construction is disabled; a pool owns its worker threads. 88   /** Copy construction is disabled; a pool owns its worker threads.
94   89  
95   @param other The pool that would be copied. 90   @param other The pool that would be copied.
96   */ 91   */
97   thread_pool(thread_pool const& other) = delete; 92   thread_pool(thread_pool const& other) = delete;
98   93  
99   /** Copy assignment is disabled; a pool owns its worker threads. 94   /** Copy assignment is disabled; a pool owns its worker threads.
100   95  
101   @param other The pool that would be assigned from. 96   @param other The pool that would be assigned from.
102   97  
103   @return A reference to `*this`. 98   @return A reference to `*this`.
104   */ 99   */
105   thread_pool& operator=(thread_pool const& other) = delete; 100   thread_pool& operator=(thread_pool const& other) = delete;
106   101  
107   /** Wait for all outstanding work to complete. 102   /** Wait for all outstanding work to complete.
108   103  
109   Releases the internal work guard, then blocks the calling 104   Releases the internal work guard, then blocks the calling
110   thread until all outstanding work tracked by 105   thread until all outstanding work tracked by
111   @ref executor_type::on_work_started and 106   @ref executor_type::on_work_started and
112   @ref executor_type::on_work_finished completes. After all 107   @ref executor_type::on_work_finished completes. After all
113   work finishes, joins the worker threads. 108   work finishes, joins the worker threads.
114   109  
115   If @ref stop is called while `join()` is blocking, the 110   If @ref stop is called while `join()` is blocking, the
116   pool stops without waiting for remaining work to 111   pool stops without waiting for remaining work to
117   complete. Worker threads finish their current item and 112   complete. Worker threads finish their current item and
118   exit; `join()` still waits for all threads to be joined 113   exit; `join()` still waits for all threads to be joined
119   before returning. 114   before returning.
120   115  
121   This function is idempotent. The first call performs the 116   This function is idempotent. The first call performs the
122   join; subsequent calls return immediately. 117   join; subsequent calls return immediately.
123   118  
124   @pre Must not be called from a thread in this pool (undefined 119   @pre Must not be called from a thread in this pool (undefined
125   behavior). 120   behavior).
126   121  
127   @par Postconditions 122   @par Postconditions
128   All worker threads have been joined. The pool cannot be 123   All worker threads have been joined. The pool cannot be
129   reused. 124   reused.
130   125  
131   @par Thread Safety 126   @par Thread Safety
132   May be called from any thread not in this pool. 127   May be called from any thread not in this pool.
133   */ 128   */
134   void 129   void
135   join() noexcept; 130   join() noexcept;
136   131  
137   /** Request all worker threads to stop. 132   /** Request all worker threads to stop.
138   133  
139   Signals all threads to exit after finishing their current 134   Signals all threads to exit after finishing their current
140   work item. Queued work that has not started is abandoned. 135   work item. Queued work that has not started is abandoned.
141   Does not wait for threads to exit. 136   Does not wait for threads to exit.
142   137  
143   If @ref join is blocking on another thread, calling 138   If @ref join is blocking on another thread, calling
144   `stop()` causes it to stop waiting for outstanding 139   `stop()` causes it to stop waiting for outstanding
145   work. The `join()` call still waits for worker threads 140   work. The `join()` call still waits for worker threads
146   to finish their current item and exit before returning. 141   to finish their current item and exit before returning.
147   142  
148   @par Thread Safety 143   @par Thread Safety
149   May be called concurrently from any thread, including a 144   May be called concurrently from any thread, including a
150   thread in this pool. 145   thread in this pool.
151   */ 146   */
152   void 147   void
153   stop() noexcept; 148   stop() noexcept;
154   149  
155   /** Return an executor for this thread pool. 150   /** Return an executor for this thread pool.
156   151  
157   @return An executor associated with this thread pool. 152   @return An executor associated with this thread pool.
158   */ 153   */
159   executor_type 154   executor_type
160   get_executor() const noexcept; 155   get_executor() const noexcept;
161   }; 156   };
162   157  
163   /** An executor that submits work to a thread_pool. 158   /** An executor that submits work to a thread_pool.
164   159  
165   Executors are lightweight handles that can be copied and stored. 160   Executors are lightweight handles that can be copied and stored.
166   All copies refer to the same underlying thread pool. 161   All copies refer to the same underlying thread pool.
167   162  
168   @par Thread Safety 163   @par Thread Safety
169   Distinct objects: Safe. 164   Distinct objects: Safe.
170   Shared objects: Safe. 165   Shared objects: Safe.
171   */ 166   */
172   class thread_pool::executor_type 167   class thread_pool::executor_type
173   { 168   {
174   friend class thread_pool; 169   friend class thread_pool;
175   170  
176   thread_pool* pool_ = nullptr; 171   thread_pool* pool_ = nullptr;
177   172  
178   explicit 173   explicit
HITCBC 179   11803 executor_type(thread_pool& pool) noexcept 174   11809 executor_type(thread_pool& pool) noexcept
HITCBC 180   11803 : pool_(&pool) 175   11809 : pool_(&pool)
181   { 176   {
HITCBC 182   11803 } 177   11809 }
183   178  
184   public: 179   public:
185   /** Construct a default null executor. 180   /** Construct a default null executor.
186   181  
187   The resulting executor is not associated with any pool. 182   The resulting executor is not associated with any pool.
188   `context()`, `dispatch()`, and `post()` require the 183   `context()`, `dispatch()`, and `post()` require the
189   executor to be associated with a pool before use. 184   executor to be associated with a pool before use.
190   */ 185   */
191   executor_type() = default; 186   executor_type() = default;
192   187  
193   /** Return the underlying thread pool. 188   /** Return the underlying thread pool.
194   189  
195   @return A reference to the associated pool. The behavior is 190   @return A reference to the associated pool. The behavior is
196   undefined if the executor is not associated with a pool. 191   undefined if the executor is not associated with a pool.
197   */ 192   */
198   thread_pool& 193   thread_pool&
HITCBC 199   12107 context() const noexcept 194   12113 context() const noexcept
200   { 195   {
HITCBC 201   12107 return *pool_; 196   12113 return *pool_;
202   } 197   }
203   198  
204   /** Notify that work has started. 199   /** Notify that work has started.
205   200  
206   Increments the outstanding work count. Must be paired 201   Increments the outstanding work count. Must be paired
207   with a subsequent call to @ref on_work_finished. 202   with a subsequent call to @ref on_work_finished.
208   203  
209   @see on_work_finished, work_guard 204   @see on_work_finished, work_guard
210   */ 205   */
211   BOOST_CAPY_DECL 206   BOOST_CAPY_DECL
212   void 207   void
213   on_work_started() const noexcept; 208   on_work_started() const noexcept;
214   209  
215   /** Notify that work has finished. 210   /** Notify that work has finished.
216   211  
217   Decrements the outstanding work count. When the count 212   Decrements the outstanding work count. When the count
218   reaches zero after @ref thread_pool::join is called, 213   reaches zero after @ref thread_pool::join is called,
219   the pool's worker threads are signaled to stop. 214   the pool's worker threads are signaled to stop.
220   215  
221   @pre A preceding call to @ref on_work_started was made. 216   @pre A preceding call to @ref on_work_started was made.
222   217  
223   @see on_work_started, work_guard 218   @see on_work_started, work_guard
224   */ 219   */
225   BOOST_CAPY_DECL 220   BOOST_CAPY_DECL
226   void 221   void
227   on_work_finished() const noexcept; 222   on_work_finished() const noexcept;
228   223  
229   /** Dispatch a continuation for execution. 224   /** Dispatch a continuation for execution.
230   225  
231   If the calling thread is a worker of this pool, returns 226   If the calling thread is a worker of this pool, returns
232   `c.h` for symmetric transfer so the caller can resume the 227   `c.h` for symmetric transfer so the caller can resume the
233   continuation inline. Otherwise, posts the continuation to 228   continuation inline. Otherwise, posts the continuation to
234   the pool for execution on a worker thread and returns 229   the pool for execution on a worker thread and returns
235   `std::noop_coroutine()`. 230   `std::noop_coroutine()`.
236   231  
237   @param c The continuation to execute. On the post path, 232   @param c The continuation to execute. On the post path,
238   must remain at a stable address until dequeued 233   must remain at a stable address until dequeued
239   and resumed. 234   and resumed.
240   235  
241   @return `c.h` when the calling thread is a pool worker; 236   @return `c.h` when the calling thread is a pool worker;
242   `std::noop_coroutine()` otherwise. 237   `std::noop_coroutine()` otherwise.
243   */ 238   */
244   BOOST_CAPY_DECL 239   BOOST_CAPY_DECL
245   std::coroutine_handle<> 240   std::coroutine_handle<>
246   dispatch(continuation& c) const; 241   dispatch(continuation& c) const;
247   242  
248   /** Post a continuation to the thread pool. 243   /** Post a continuation to the thread pool.
249   244  
250   The continuation is resumed on one of the pool's 245   The continuation is resumed on one of the pool's
251   worker threads. The continuation must remain at a stable 246   worker threads. The continuation must remain at a stable
252   address until it is dequeued and resumed. 247   address until it is dequeued and resumed.
253   248  
254   @param c The continuation to execute. 249   @param c The continuation to execute.
255   */ 250   */
256   BOOST_CAPY_DECL 251   BOOST_CAPY_DECL
257   void 252   void
258   post(continuation& c) const; 253   post(continuation& c) const;
259   254  
260   /** Return true if two executors refer to the same thread pool. 255   /** Return true if two executors refer to the same thread pool.
261   256  
262   @param other The executor to compare against. 257   @param other The executor to compare against.
263   258  
264   @return `true` if both executors refer to the same pool. 259   @return `true` if both executors refer to the same pool.
265   */ 260   */
266   bool 261   bool
HITCBC 267   13 operator==(executor_type const& other) const noexcept 262   13 operator==(executor_type const& other) const noexcept
268   { 263   {
HITCBC 269   13 return pool_ == other.pool_; 264   13 return pool_ == other.pool_;
270   } 265   }
271   }; 266   };
272   267  
273   } // capy 268   } // capy
274   } // boost 269   } // boost
275   270  
276   #endif 271   #endif