include/boost/capy/ex/async_waker.hpp

95.8% Lines (92 / 96, 13 excl) 100.0% Functions (13 / 13)
async_waker.hpp
f(x) Functions (13)
Line TLA Hits Source Code
1 //
2 // Copyright (c) 2026 Steve Gerbino
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_ASYNC_WAKER_HPP
12 #define BOOST_CAPY_EX_ASYNC_WAKER_HPP
13
14 #include <boost/capy/detail/config.hpp>
15 #include <boost/capy/continuation.hpp>
16 #include <boost/capy/error.hpp>
17 #include <boost/capy/ex/executor_ref.hpp>
18 #include <boost/capy/ex/await_context.hpp>
19 #include <boost/capy/results.hpp>
20
21 #include <atomic>
22 #include <coroutine>
23 #include <new>
24 #include <stop_token>
25 #include <thread>
26 #include <utility>
27
28 /* async_waker implementation notes
29 ===================================
30
31 wake() must be callable from foreign threads (that is the whole
32 point: the user's thread provides the timing). A waiter-side
33 claimed_ flag is not enough there, because the
34 waker has to dereference the waiter, and nothing would pin the
35 waiter's frame between reading the pointer and claiming it.
36
37 So the st_ atomic is the single arbiter:
38
39 empty --arm--> arming --publish--> armed --wake/cancel CAS--> empty
40 arming --stop already requested--> empty
41 empty --wake--> token --wait consumes--> empty
42
43 Whoever wins the armed->empty CAS owns the resume and may
44 dereference waiter_: the frame cannot die underneath the
45 winner because the coroutine only resumes when the winner
46 posts it. The loser never touches the waiter. When the stop
47 callback wins, a concurrent wake retries, finds empty, and
48 latches a token -- a racing wakeup is deferred, never lost.
49
50 The stop callback is registered before the waiter enters the
51 arming state, and a wake() winner destroys it before posting.
52 While arming, nothing can claim the waiter: wake(), the stop
53 callback and the destructor wait the few instructions it takes.
54 So the waiter settles a stop requested during registration
55 itself, its last touch of the waker is the publishing store,
56 and the waker can die right after the wake() that claimed it.
57
58 Serialized resumption is still required: the executor must not
59 run the waiter's continuations concurrently, since a winner can
60 post the waiter before its await_suspend has returned. async_event
61 and async_mutex make the same assumption; it is stated explicitly
62 here because wake() invites foreign threads into the picture.
63 */
64
65 namespace boost {
66 namespace capy {
67
68 /** Hand a wakeup from any thread to one waiting coroutine, latching it if none waits.
69
70 Use this to resume a coroutine from an external event, such as a
71 timer thread. The user provides the thread and the clock, and capy
72 provides the suspension point. One coroutine suspends in `wait()`;
73 any thread wakes it with `wake()`.
74
75 A wakeup with no waiter present is latched as a single pending
76 token, and the next `wait()` consumes it immediately. This
77 makes the wake-before-wait race benign without any lock
78 protocol. Multiple wakes collapse into one token.
79
80 @par Cancellation
81
82 If the environment's stop token is triggered while suspended,
83 the wait completes with `error::canceled`. A wake that loses
84 the race against cancellation is latched for the next `wait()`
85 rather than dropped.
86
87 @par Zero Allocation
88
89 No heap allocation occurs for wait or wake operations.
90
91 @par Thread Safety
92
93 Distinct objects: Safe.@n
94 Shared objects: `wake()` may be called from any thread.
95 `wait()` must only be awaited by one coroutine at a time. The
96 executor must never run the coroutine's continuations
97 concurrently: use a single-threaded executor, or a strand over
98 a multi-threaded one. That is the same threading model as
99 `async_event` and `async_mutex`. Awaiting `wait()` directly
100 on a multi-threaded executor is undefined.
101
102 This type is non-copyable and non-movable because a suspended
103 waiter holds a pointer into the object.
104
105 @par Example
106 @par !example example
107
108 */
109 class async_waker
110 {
111 public:
112 class wait_awaiter;
113
114 private:
115 static constexpr int state_empty = 0; // no token, no waiter
116 static constexpr int state_token = 1; // latched wakeup
117 static constexpr int state_armed = 2; // waiter suspended
118 static constexpr int state_arming = 3; // waiter publishing itself
119
120 std::atomic<int> st_{state_empty};
121 wait_awaiter* waiter_ = nullptr;
122
123 // Take the armed waiter, waiting out one still publishing itself.
124 2428x bool claim_armed() noexcept
125 {
126 2428x int expected = state_armed;
127 for(;;)
128 {
129 4856x if(st_.compare_exchange_weak(
130 expected, state_empty,
131 std::memory_order_acq_rel,
132 std::memory_order_acquire))
133 2012x return true;
134 416x if(expected == state_armed)
135 − continue; // LCOV_EXCL_LINE spurious weak CAS failure
136 416x if(expected != state_arming)
137 416x return false;
138 − std::this_thread::yield(); // LCOV_EXCL_LINE race with a waiter still publishing itself
139 − expected = state_armed; // LCOV_EXCL_LINE race with a waiter still publishing itself
140 }
141 }
142
143 public:
144 /** Suspends the caller until `wake()` runs, or resumes it with `error::canceled` on a stop request.
145 */
146 class wait_awaiter
147 {
148 friend class async_waker;
149
150 async_waker* waker_;
151 continuation cont_;
152 executor_ref ex_;
153
154 // Declared before stop_cb_buf_: the callback accesses
155 // these members, so they must still be alive if the
156 // stop_cb_ destructor blocks.
157 bool canceled_ = false;
158 bool active_ = false;
159 bool published_ = false;
160
161 // Set by whoever wins the armed->empty transition, before it
162 // posts. A claimed waiter belongs to the executor's queue and
163 // may be discarded after the waker is gone, so its destructor
164 // must not touch the waker.
165 std::atomic<bool> claimed_{false};
166
167 struct cancel_fn
168 {
169 wait_awaiter* self_;
170
171 2010x void operator()() const noexcept
172 {
173 2010x if(self_->waker_->claim_armed())
174 {
175 2010x self_->canceled_ = true;
176 2010x self_->claimed_.store(
177 true, std::memory_order_release);
178 2010x self_->ex_.post(self_->cont_);
179 }
180 2010x }
181 };
182
183 using stop_cb_t = std::stop_callback<cancel_fn>;
184
185 // Aligned storage for stop_cb_t. Declared last: its
186 // destructor may block while the callback accesses the
187 // members above.
188 BOOST_CAPY_MSVC_WARNING_PUSH
189 BOOST_CAPY_MSVC_WARNING_DISABLE(4324)
190 alignas(stop_cb_t)
191 unsigned char stop_cb_buf_[sizeof(stop_cb_t)];
192 BOOST_CAPY_MSVC_WARNING_POP
193
194 2340x stop_cb_t& stop_cb_() noexcept
195 {
196 2340x return *reinterpret_cast<stop_cb_t*>(stop_cb_buf_);
197 }
198
199 public:
200 /** Destroy the awaiter, leaving the waker unable to reach it.
201
202 Destroys the stop callback if one is registered. If the awaiter
203 is still armed, it also returns the waker's slot to the empty
204 state, so a later `wake()` cannot dereference a destroyed
205 awaiter. That case means the frame is being torn down without
206 ever being resumed; a wake arriving afterward latches a token
207 instead.
208 */
209 4904x ~wait_awaiter()
210 {
211 4904x if(active_)
212 2x stop_cb_().~stop_cb_t();
213 4908x if(published_ &&
214 4x !claimed_.load(std::memory_order_acquire))
215 {
216 // Destroyed while still armed (frame torn down
217 // without resuming): deregister so a later
218 // wake cannot touch the dead frame.
219 1x int expected = state_armed;
220 1x waker_->st_.compare_exchange_strong(
221 expected, state_empty,
222 std::memory_order_acq_rel,
223 std::memory_order_acquire);
224 }
225 4904x }
226
227 /** Construct an awaiter for the given waker.
228
229 @param waker The waker to wait on. It must outlive the awaiter.
230 */
231 2452x explicit wait_awaiter(async_waker* waker) noexcept
232 2452x : waker_(waker)
233 {
234 2452x }
235
236 /** Construct by moving.
237
238 The moved-from awaiter is left inert: its destructor no longer
239 destroys the stop callback and no longer deregisters from the
240 waker.
241
242 @pre The source has not been suspended (its `await_suspend`
243 has not armed the waker).
244
245 @param o The awaiter to move from.
246 */
247 2452x wait_awaiter(wait_awaiter&& o) noexcept
248 2452x : waker_(o.waker_)
249 2452x , cont_(o.cont_)
250 2452x , ex_(o.ex_)
251 2452x , canceled_(o.canceled_)
252 2452x , active_(std::exchange(o.active_, false))
253 2452x , published_(std::exchange(o.published_, false))
254 2452x , claimed_(o.claimed_.load(std::memory_order_relaxed))
255 {
256 2452x }
257
258 /** Copy construction is disabled; an armed waiter is registered
259 with the waker by address.
260
261 @param other The awaiter that would be copied.
262 */
263 wait_awaiter(wait_awaiter const& other) = delete;
264
265 /** Copy assignment is disabled; an armed waiter is registered
266 with the waker by address.
267
268 @param other The awaiter that would be assigned from.
269
270 @return A reference to `*this`.
271 */
272 wait_awaiter& operator=(wait_awaiter const& other) = delete;
273
274 /** Move assignment is disabled; an armed waiter is registered
275 with the waker by address.
276
277 @param other The awaiter that would be moved from.
278
279 @return A reference to `*this`.
280 */
281 wait_awaiter& operator=(wait_awaiter&& other) = delete;
282
283 /** Consume a latched token, completing synchronously.
284
285 This is not a pure query: the check is a compare-exchange that
286 takes the token. Calling it twice is not idempotent: the second
287 call reports `false`, because the first already consumed the
288 wakeup. On `true` the awaiting coroutine does not suspend.
289
290 @return `true` if a latched wakeup token was consumed; else `false`.
291 */
292 2452x bool await_ready() noexcept
293 {
294 2452x int expected = state_token;
295 2452x return waker_->st_.compare_exchange_strong(
296 expected, state_empty,
297 std::memory_order_acq_rel,
298 2452x std::memory_order_acquire);
299 }
300
301 /** Arm the waker with the awaiting coroutine.
302
303 This is the @ref ContextAwaitable overload of `await_suspend`.
304 Unlike `async_event` and `async_mutex`, it has three outcomes,
305 because a `wake()` from another thread can land in the window
306 between `await_ready` and this call.
307
308 @li A stop request is already pending on `env->stop_token`: the
309 awaiter records the cancellation and does not arm.
310
311 @li The waker's slot is no longer empty. Under the single-waiter
312 precondition that means a wakeup was latched after
313 `await_ready` looked, so the token is consumed here instead
314 and the wait succeeds.
315
316 @li Otherwise a stop callback is registered on
317 `env->stop_token`. A stop requested during registration
318 cancels the wait at once. Otherwise the awaiter suspends.
319 Exactly one of `wake()`, a stop request and the waker's
320 destructor then completes the wait, posting `h` through
321 `env->executor`. A `wake()` that loses to a stop request
322 latches its token for the next `wait()`.
323
324 @param h The awaiting coroutine, resumed when the waker fires
325 or the wait is canceled.
326
327 @param env The execution environment. Its executor posts the
328 resumption and its stop token is watched for the duration of
329 the wait. It must outlive the wait.
330
331 A returned `h` resumes the awaiting coroutine at once. A
332 returned `std::noop_coroutine()` leaves the coroutine suspended
333 and returns control to the resumer.
334
335 @return `h` if the wait ended without suspending, else `noop_coroutine()`.
336 */
337 std::coroutine_handle<>
338 2367x await_suspend(
339 std::coroutine_handle<> h,
340 await_context const* env) noexcept
341 {
342 2367x if(env->stop_token.stop_requested())
343 {
344 27x canceled_ = true;
345 27x return h;
346 }
347 2340x cont_.h = h;
348 2340x cont_.owner = env->owner;
349 2340x ex_ = env->executor;
350 2340x waker_->waiter_ = this;
351
352 // Registered before publishing, so the wake() that claims
353 // this waiter can deregister it before posting.
354 7020x ::new(stop_cb_buf_) stop_cb_t(
355 2340x env->stop_token, cancel_fn{this});
356 2340x active_ = true;
357 2340x published_ = true;
358
359 2340x int expected = state_empty;
360 4680x if(!waker_->st_.compare_exchange_strong(
361 expected, state_arming,
362 std::memory_order_acq_rel,
363 std::memory_order_acquire))
364 {
365 // LCOV_EXCL_START race: a wake latched between await_ready and here
366 // Single-waiter precondition: a second concurrent
367 // wait would find the slot armed.
368 − BOOST_CAPY_ASSERT(expected == state_token);
369
370 // A wake latched between await_ready and here;
371 // consume it and resume inline.
372 − published_ = false;
373 − stop_cb_().~stop_cb_t();
374 − active_ = false;
375 − waker_->st_.store(
376 state_empty, std::memory_order_release);
377 − return h;
378 // LCOV_EXCL_STOP
379 }
380
381 // While arming nothing else can claim this waiter, so a stop
382 // requested as the callback registered is settled here, and
383 // the waker is not touched again once the waiter is armed.
384 2340x if(env->stop_token.stop_requested())
385 {
386 ✗ published_ = false;
387 ✗ waker_->st_.store(
388 state_empty, std::memory_order_release);
389 ✗ canceled_ = true;
390 ✗ return h;
391 }
392 2340x waker_->st_.store(state_armed, std::memory_order_release);
393 2340x return std::noop_coroutine();
394 }
395
396 /** Complete the wait and report the outcome.
397
398 Destroys the stop callback if one is registered and clears the
399 armed bookkeeping, so the destructor does not deregister a slot
400 the resumption already consumed. A wakeup is either a `wake()`
401 or a token consumed inline. An `error::canceled` result means
402 the stop token won the race or the waker was destroyed.
403
404 @return Empty if woken, else `error::canceled`.
405 */
406 2448x [[nodiscard]] results<> await_resume() noexcept
407 {
408 2448x if(active_)
409 {
410 2009x stop_cb_().~stop_cb_t();
411 2009x active_ = false;
412 }
413 2448x published_ = false;
414 2448x if(canceled_)
415 2038x return {make_error_code(error::canceled)};
416 410x return {{}};
417 }
418 };
419
420 /// Construct with no token latched.
421 307x async_waker() = default;
422
423 /** Destroy the waker, canceling a coroutine still waiting.
424
425 The waiter is posted to its executor to resume with
426 `error::canceled`, as if its stop token had been triggered. An
427 executor that can no longer run it abandons it instead, possibly
428 before this destructor returns. Either way the waiter no longer
429 refers to the waker.
430
431 @pre No `wake()` call is in progress or made afterward.
432
433 @note If posting the waiter's resumption throws, `std::terminate`
434 is called.
435 */
436 418x ~async_waker()
437 {
438 418x if(claim_armed())
439 {
440 2x auto* w = waiter_;
441 // The stop callback reaches into the waker; deregistering
442 // it waits out one already running.
443 2x if(w->active_)
444 {
445 using cb_t = wait_awaiter::stop_cb_t;
446 2x w->stop_cb_().~cb_t();
447 2x w->active_ = false;
448 }
449 2x w->canceled_ = true;
450 2x w->claimed_.store(true, std::memory_order_release);
451 2x w->ex_.post(w->cont_);
452 }
453 418x }
454
455 /** Copy construction is disabled; an armed waiter points into the
456 waker.
457
458 @param other The waker that would be copied.
459 */
460 async_waker(async_waker const& other) = delete;
461
462 /** Copy assignment is disabled; an armed waiter points into the waker.
463
464 @param other The waker that would be assigned from.
465
466 @return A reference to `*this`.
467 */
468 async_waker& operator=(async_waker const& other) = delete;
469
470 /** Move construction is disabled; an armed waiter points into the
471 waker.
472
473 @param other The waker that would be moved from.
474 */
475 async_waker(async_waker&& other) = delete;
476
477 /** Move assignment is disabled; an armed waiter points into the waker.
478
479 @param other The waker that would be moved from.
480
481 @return A reference to `*this`.
482 */
483 async_waker& operator=(async_waker&& other) = delete;
484
485 /** Asynchronously wait until woken.
486
487 If a token is latched, completes immediately and consumes
488 it. Otherwise suspends until `wake()` or the stop token
489 fires.
490
491 The awaitable's result is empty on wakeup, or
492 `error::canceled` if the stop token wins.
493
494 @pre No other coroutine is currently waiting on this object; a
495 coroutine woken or canceled but not yet resumed still is.
496
497 @return An awaitable that await-returns `(error_code)`.
498 */
499 2452x wait_awaiter wait() noexcept
500 {
501 2452x return wait_awaiter{this};
502 }
503
504 /** Wake the waiter, or latch the wakeup if none waits.
505
506 Callable from any thread. The waiter's resumption is
507 posted through its executor; this call never resumes a
508 coroutine inline. Multiple calls without an intervening
509 `wait()` collapse into a single token. It may wait briefly
510 for a waiter that is still suspending, or for a stop callback
511 of the waiter that is running on another thread.
512
513 @note If posting the waiter's resumption throws, `std::terminate`
514 is called.
515 */
516 414x void wake() noexcept
517 {
518 for(;;)
519 {
520 414x int s = st_.load(std::memory_order_acquire);
521 414x if(s == state_token)
522 414x return;
523 412x if(s == state_empty)
524 {
525 170x if(st_.compare_exchange_weak(
526 s, state_token,
527 std::memory_order_acq_rel,
528 std::memory_order_acquire))
529 85x return;
530 − continue; // LCOV_EXCL_LINE spurious weak CAS failure
531 }
532 // The waiter is still publishing itself; it settles in a
533 // few instructions.
534 327x if(s == state_arming)
535 {
536 − std::this_thread::yield(); // LCOV_EXCL_LINE race with a waiter still publishing itself
537 − continue; // LCOV_EXCL_LINE race with a waiter still publishing itself
538 }
539 // armed: winning this CAS claims the waiter, whose
540 // frame is pinned until we post its resumption.
541 654x if(st_.compare_exchange_weak(
542 s, state_empty,
543 std::memory_order_acq_rel,
544 std::memory_order_acquire))
545 {
546 327x auto* w = waiter_;
547 // Nothing may reach this waker once the waiter is
548 // posted; this waits out a stop callback already
549 // running, which then finds the slot empty.
550 using cb_t = wait_awaiter::stop_cb_t;
551 327x w->stop_cb_().~cb_t();
552 327x w->active_ = false;
553 327x w->claimed_.store(true, std::memory_order_release);
554 327x w->ex_.post(w->cont_);
555 327x return;
556 }
557 − } // LCOV_EXCL_LINE armed CAS lost to a stop callback or failed spuriously
558 }
559 };
560
561 } // namespace capy
562 } // namespace boost
563
564 #endif
565