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