100.00% Lines (28/28) 100.00% Functions (13/13)
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_STRAND_HPP 11   #ifndef BOOST_CAPY_EX_STRAND_HPP
12   #define BOOST_CAPY_EX_STRAND_HPP 12   #define BOOST_CAPY_EX_STRAND_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/detail/strand_service.hpp> 17   #include <boost/capy/ex/detail/strand_service.hpp>
18   18  
19   #include <type_traits> 19   #include <type_traits>
20   20  
21   namespace boost { 21   namespace boost {
22   namespace capy { 22   namespace capy {
23   23  
24   /** Provides serialized coroutine execution for any executor type. 24   /** Provides serialized coroutine execution for any executor type.
25   25  
26   A strand wraps an inner executor and ensures that coroutines 26   A strand wraps an inner executor and ensures that coroutines
27   dispatched through it never run concurrently. At most one 27   dispatched through it never run concurrently. At most one
28   coroutine executes at a time within a strand, even when the 28   coroutine executes at a time within a strand, even when the
29   underlying executor runs on multiple threads. 29   underlying executor runs on multiple threads.
30   30  
31   Strands are lightweight handles that can be copied freely. 31   Strands are lightweight handles that can be copied freely.
32   Copies share the same internal serialization state, so 32   Copies share the same internal serialization state, so
33   coroutines dispatched through any copy are serialized with 33   coroutines dispatched through any copy are serialized with
34   respect to all other copies. 34   respect to all other copies.
35   35  
36   @par Invariant 36   @par Invariant
37   Coroutines resumed through a strand shall not run concurrently. 37   Coroutines resumed through a strand shall not run concurrently.
38 - @par Implementation  
39 - Each strand allocates a private serialization state. Strands  
40 - constructed from the same execution context share a small pool  
41 - of mutexes (193 entries) selected by hash. Mutex sharing causes  
42 - only brief contention on the push/pop critical section, never  
43 - cross-strand state sharing. Construction cost: one  
44 - `std::make_shared` per strand.  
45 -  
46   38  
47   @par Executor Concept 39   @par Executor Concept
48   This class satisfies the `Executor` concept, providing: 40   This class satisfies the `Executor` concept, providing:
49 - - `context()` - Returns the underlying execution context 41 + - `context()` returns the underlying execution context.
50 - - `on_work_started()` / `on_work_finished()` - Work tracking 42 + - `on_work_started()` and `on_work_finished()` track work.
51 - - `dispatch(continuation&)` - May run immediately if already executing in this strand 43 + - `dispatch(continuation&)` may resume inline when already in this strand.
52 - - `post(continuation&)` - Always queues for later execution 44 + - `post(continuation&)` always queues for later execution.
53   45  
54 - @par Preconditions 46 + @pre A strand holds only a non-owning reference to its inner executor's
55 - A strand holds only a non-owning reference to its inner executor's  
56   execution context (for example a `thread_pool`). That context must 47   execution context (for example a `thread_pool`). That context must
57   outlive every post() and dispatch() call; posting or dispatching 48   outlive every post() and dispatch() call; posting or dispatching
58   concurrently with, or after, the context's destruction is undefined 49   concurrently with, or after, the context's destruction is undefined
59   behavior. To guarantee this, submit work through @ref run_async or 50   behavior. To guarantee this, submit work through @ref run_async or
60   @ref run. Their operations are work-tracked, so the context's 51   @ref run. Their operations are work-tracked, so the context's
61   `join()` waits for them. Call `join()` on the context before 52   `join()` waits for them. Call `join()` on the context before
62   destroying it, rather than posting to a strand from an external 53   destroying it, rather than posting to a strand from an external
63   thread the context does not track. Destroying the strand handle 54   thread the context does not track. Destroying the strand handle
64   itself is always safe, including after the context is 55   itself is always safe, including after the context is
65   destroyed. 56   destroyed.
66   57  
67   Coroutines queued on the strand when its context shuts down are 58   Coroutines queued on the strand when its context shuts down are
68   passed to @ref abandon rather than resumed. 59   passed to @ref abandon rather than resumed.
69   60  
70   @par Thread Safety 61   @par Thread Safety
71   Distinct objects: Safe. 62   Distinct objects: Safe.
72   Shared objects: Safe. 63   Shared objects: Safe.
73   64  
74   @par Example 65   @par Example
75   @par !example example 66   @par !example example
76   67  
77   68  
78   @tparam Ex The type of the underlying executor. Must 69   @tparam Ex The type of the underlying executor. Must
79   satisfy the `Executor` concept. 70   satisfy the `Executor` concept.
80   71  
81   @see @ref Executor 72   @see @ref Executor
82   */ 73   */
83   template<typename Ex> 74   template<typename Ex>
84   class strand 75   class strand
85   { 76   {
86   std::shared_ptr<detail::strand_impl> impl_; 77   std::shared_ptr<detail::strand_impl> impl_;
87   Ex ex_; 78   Ex ex_;
88   79  
89   friend struct strand_test; 80   friend struct strand_test;
90   81  
91   public: 82   public:
92 - /** Names the executor type this `strand<Ex>` wraps. 83 + /// Names the executor type this `strand<Ex>` wraps.
93 - */  
94   using inner_executor_type = Ex; 84   using inner_executor_type = Ex;
95   85  
96   /** Construct a strand for the specified executor. 86   /** Construct a strand for the specified executor.
97   87  
98   Allocates a fresh strand implementation from the service 88   Allocates a fresh strand implementation from the service
99   associated with the executor's context. 89   associated with the executor's context.
100   90  
  91 + @throws std::bad_alloc If allocation fails.
  92 +
101   @param ex The inner executor to wrap. Coroutines are 93   @param ex The inner executor to wrap. Coroutines are
102   ultimately dispatched through this executor. 94   ultimately dispatched through this executor.
103   95  
104   @note This constructor is disabled if the argument is a 96   @note This constructor is disabled if the argument is a
105   strand type, to prevent strand-of-strand wrapping. 97   strand type, to prevent strand-of-strand wrapping.
106   */ 98   */
107   template<typename Ex1, 99   template<typename Ex1,
108   typename = std::enable_if_t< 100   typename = std::enable_if_t<
109   !std::is_same_v<std::decay_t<Ex1>, strand> && 101   !std::is_same_v<std::decay_t<Ex1>, strand> &&
110   !detail::is_strand<std::decay_t<Ex1>>::value && 102   !detail::is_strand<std::decay_t<Ex1>>::value &&
111   std::is_convertible_v<Ex1, Ex>>> 103   std::is_convertible_v<Ex1, Ex>>>
112   explicit 104   explicit
HITCBC 113   12468 strand(Ex1&& ex) 105   12468 strand(Ex1&& ex)
HITCBC 114   12468 : impl_(detail::get_strand_service(ex.context()) 106   12468 : impl_(detail::get_strand_service(ex.context())
HITCBC 115   12468 .create_implementation()) 107   12468 .create_implementation())
HITCBC 116   12468 , ex_(std::forward<Ex1>(ex)) 108   12468 , ex_(std::forward<Ex1>(ex))
117   { 109   {
HITCBC 118   12468 } 110   12468 }
119   111  
120   /** Construct a copy. 112   /** Construct a copy.
121   113  
122   Creates a strand that shares serialization state with 114   Creates a strand that shares serialization state with
123   the original. Coroutines dispatched through either strand 115   the original. Coroutines dispatched through either strand
124   are serialized with respect to each other. 116   are serialized with respect to each other.
125   117  
126   @param other The strand to copy. 118   @param other The strand to copy.
127   */ 119   */
HITCBC 128   100015 strand(strand const& other) = default; 120   100015 strand(strand const& other) = default;
129   121  
130   /** Construct by moving. 122   /** Construct by moving.
131   123  
132   @param other The strand to move from. 124   @param other The strand to move from.
133   125  
134   @note A moved-from strand is only safe to destroy 126   @note A moved-from strand is only safe to destroy
135   or reassign. 127   or reassign.
136   */ 128   */
HITCBC 137   511479 strand(strand&& other) = default; 129   511479 strand(strand&& other) = default;
138   130  
139   /** Assign by copying. 131   /** Assign by copying.
140   132  
141   Shares serialization state with `other`, as the copy 133   Shares serialization state with `other`, as the copy
142   constructor does. 134   constructor does.
143   135  
144   @param other The strand to copy. 136   @param other The strand to copy.
145   137  
146   @return A reference to `*this`. 138   @return A reference to `*this`.
147   */ 139   */
HITCBC 148   1 strand& operator=(strand const& other) = default; 140   1 strand& operator=(strand const& other) = default;
149   141  
150   /** Assign by moving. 142   /** Assign by moving.
151   143  
152   @param other The strand to move from. 144   @param other The strand to move from.
153   145  
154   @return A reference to `*this`. 146   @return A reference to `*this`.
155   147  
156   @note A moved-from strand is only safe to destroy 148   @note A moved-from strand is only safe to destroy
157   or reassign. 149   or reassign.
158   */ 150   */
HITCBC 159   1 strand& operator=(strand&& other) = default; 151   1 strand& operator=(strand&& other) = default;
160   152  
161   /** Return the underlying executor. 153   /** Return the underlying executor.
162   154  
163   @return A const reference to the inner executor. 155   @return A const reference to the inner executor.
164   */ 156   */
165   Ex const& 157   Ex const&
HITCBC 166   1 get_inner_executor() const noexcept 158   1 get_inner_executor() const noexcept
167   { 159   {
HITCBC 168   1 return ex_; 160   1 return ex_;
169   } 161   }
170   162  
171   /** Return the underlying execution context. 163   /** Return the underlying execution context.
172   164  
173   @return A reference to the execution context associated 165   @return A reference to the execution context associated
174   with the inner executor. 166   with the inner executor.
175   */ 167   */
176   auto& 168   auto&
HITCBC 177   100006 context() const noexcept 169   100006 context() const noexcept
178   { 170   {
HITCBC 179   100006 return ex_.context(); 171   100006 return ex_.context();
180   } 172   }
181   173  
182   /** Notify that work has started. 174   /** Notify that work has started.
183   175  
184   Delegates to the inner executor's `on_work_started()`. For a 176   Delegates to the inner executor's `on_work_started()`. For a
185   `thread_pool` inner executor, this increments the count that 177   `thread_pool` inner executor, this increments the count that
186   `join()` blocks on. 178   `join()` blocks on.
187   */ 179   */
188   void 180   void
HITCBC 189   100012 on_work_started() const noexcept 181   100012 on_work_started() const noexcept
190   { 182   {
HITCBC 191   100012 ex_.on_work_started(); 183   100012 ex_.on_work_started();
HITCBC 192   100012 } 184   100012 }
193   185  
194   /** Notify that work has finished. 186   /** Notify that work has finished.
195   187  
196   Delegates to the inner executor's `on_work_finished()`. For a 188   Delegates to the inner executor's `on_work_finished()`. For a
197   `thread_pool` inner executor, this decrements the count that 189   `thread_pool` inner executor, this decrements the count that
198   `join()` blocks on. 190   `join()` blocks on.
199   */ 191   */
200   void 192   void
HITCBC 201   100012 on_work_finished() const noexcept 193   100012 on_work_finished() const noexcept
202   { 194   {
HITCBC 203   100012 ex_.on_work_finished(); 195   100012 ex_.on_work_finished();
HITCBC 204   100012 } 196   100012 }
205   197  
206 - /** Determine whether the strand is running in the current thread. 198 + /** Check whether the strand is running in the current thread.
207   199  
208   @return true if the current thread is executing a coroutine 200   @return true if the current thread is executing a coroutine
209   within this strand's dispatch loop. 201   within this strand's dispatch loop.
210   */ 202   */
211   bool 203   bool
HITCBC 212   4 running_in_this_thread() const noexcept 204   4 running_in_this_thread() const noexcept
213   { 205   {
HITCBC 214   4 return detail::strand_service::running_in_this_thread(*impl_); 206   4 return detail::strand_service::running_in_this_thread(*impl_);
215   } 207   }
216   208  
217   /** Compare two strands for equality. 209   /** Compare two strands for equality.
218   210  
219   Two strands are equal if they share the same internal 211   Two strands are equal if they share the same internal
220   serialization state. Equal strands serialize coroutines 212   serialization state. Equal strands serialize coroutines
221   with respect to each other. 213   with respect to each other.
222   214  
223   @param other The strand to compare against. 215   @param other The strand to compare against.
224   @return true if both strands share the same implementation. 216   @return true if both strands share the same implementation.
225   */ 217   */
226   bool 218   bool
HITCBC 227   499505 operator==(strand const& other) const noexcept 219   499505 operator==(strand const& other) const noexcept
228   { 220   {
HITCBC 229   499505 return impl_.get() == other.impl_.get(); 221   499505 return impl_.get() == other.impl_.get();
230   } 222   }
231   223  
232   /** Post a continuation to the strand. 224   /** Post a continuation to the strand.
233   225  
234   The continuation is always queued for execution, never resumed 226   The continuation is always queued for execution, never resumed
235   immediately. When the strand becomes available, queued 227   immediately. When the strand becomes available, queued
236   work executes in FIFO order on the underlying executor. 228   work executes in FIFO order on the underlying executor.
237   229  
  230 + @pre The strand's execution context must outlive this call.
  231 + Posting concurrently with, or after, that context's destruction
  232 + is undefined behavior.
  233 +
238   @par Ordering 234   @par Ordering
239   Guarantees strict FIFO ordering relative to other post() calls. 235   Guarantees strict FIFO ordering relative to other post() calls.
240   Use this instead of dispatch() when ordering matters. 236   Use this instead of dispatch() when ordering matters.
241   237  
  238 + @par Exception Safety
  239 + If this throws, `c` is not queued and the caller still holds it.
  240 +
  241 + @throws std::bad_alloc If allocation fails.
  242 + @throws Any exception thrown by the inner executor's `post`.
  243 +
242   @param c The continuation to post. The caller retains 244   @param c The continuation to post. The caller retains
243   ownership; the continuation must remain valid until 245   ownership; the continuation must remain valid until
244 -  
245 - @par Preconditions  
246 - The strand's execution context must outlive this call. Posting  
247 - concurrently with, or after, that context's destruction is  
248 - undefined behavior.  
249   it is dequeued and resumed. 246   it is dequeued and resumed.
250   */ 247   */
251   void 248   void
HITCBC 252   231431 post(continuation& c) const 249   231431 post(continuation& c) const
253   { 250   {
HITCBC 254   231431 detail::strand_service::post(impl_, executor_ref(ex_), c); 251   231431 detail::strand_service::post(impl_, executor_ref(ex_), c);
HITCBC 255   231427 } 252   231427 }
256   253  
257   /** Dispatch a continuation through the strand. 254   /** Dispatch a continuation through the strand.
258   255  
259   Returns a handle for symmetric transfer. If the calling 256   Returns a handle for symmetric transfer. If the calling
260   thread is already executing within this strand, returns `c.h`. 257   thread is already executing within this strand, returns `c.h`.
261   Otherwise, the continuation is queued and 258   Otherwise, the continuation is queued and
262   `std::noop_coroutine()` is returned. 259   `std::noop_coroutine()` is returned.
263   260  
  261 + @pre The strand's execution context must outlive this call.
  262 + Dispatching concurrently with, or after, that context's
  263 + destruction is undefined behavior.
  264 +
264   @par Ordering 265   @par Ordering
265   Callers requiring strict FIFO ordering should use post() 266   Callers requiring strict FIFO ordering should use post()
266   instead, which always queues the continuation. 267   instead, which always queues the continuation.
267   268  
  269 + @par Exception Safety
  270 + If this throws, `c` is not queued and the caller still holds it.
  271 +
  272 + @throws std::bad_alloc If allocation fails.
  273 + @throws Any exception thrown by the inner executor's `post`.
  274 +
268   @param c The continuation to dispatch. The caller retains 275   @param c The continuation to dispatch. The caller retains
269   ownership; the continuation must remain valid until 276   ownership; the continuation must remain valid until
270   it is dequeued and resumed. 277   it is dequeued and resumed.
271   278  
272 -  
273 - @par Preconditions  
274 - The strand's execution context must outlive this call.  
275 - Dispatching concurrently with, or after, that context's  
276 - destruction is undefined behavior.  
277   @return A handle for symmetric transfer or `std::noop_coroutine()`. 279   @return A handle for symmetric transfer or `std::noop_coroutine()`.
278   */ 280   */
279   std::coroutine_handle<> 281   std::coroutine_handle<>
HITCBC 280   100013 dispatch(continuation& c) const 282   100013 dispatch(continuation& c) const
281   { 283   {
HITCBC 282   100013 return detail::strand_service::dispatch(impl_, executor_ref(ex_), c); 284   100013 return detail::strand_service::dispatch(impl_, executor_ref(ex_), c);
283   } 285   }
284   }; 286   };
285   287  
286   /** Deduce the executor type from the constructor argument. 288   /** Deduce the executor type from the constructor argument.
287   289  
288   @tparam Ex The wrapped executor type. 290   @tparam Ex The wrapped executor type.
289   */ 291   */
290   template<typename Ex> 292   template<typename Ex>
291   strand(Ex) -> strand<Ex>; 293   strand(Ex) -> strand<Ex>;
292   294  
293   } // namespace capy 295   } // namespace capy
294   } // namespace boost 296   } // namespace boost
295   297  
296   #endif 298   #endif