TLA Line data Source code
1 : //
2 : // Copyright (c) 2026 Michael Vandeberg
3 : // Copyright (c) 2026 Steve Gerbino
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_WHEN_ANY_HPP
12 : #define BOOST_CAPY_WHEN_ANY_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/detail/results_combinators.hpp>
16 : #include <boost/capy/continuation.hpp>
17 : #include <boost/capy/concept/executor.hpp>
18 : #include <boost/capy/concept/context_awaitable.hpp>
19 : #include <coroutine>
20 : #include <boost/capy/ex/executor_ref.hpp>
21 : #include <boost/capy/ex/abandon.hpp>
22 : #include <boost/capy/detail/owned_range.hpp>
23 : #include <boost/capy/ex/frame_alloc_mixin.hpp>
24 : #include <boost/capy/ex/frame_allocator.hpp>
25 : #include <boost/capy/ex/await_context.hpp>
26 : #include <boost/capy/task.hpp>
27 :
28 : #include <array>
29 : #include <atomic>
30 : #include <exception>
31 : #include <memory>
32 : #include <mutex>
33 : #include <optional>
34 : #include <ranges>
35 : #include <stdexcept>
36 : #include <stop_token>
37 : #include <tuple>
38 : #include <type_traits>
39 : #include <utility>
40 : #include <variant>
41 : #include <vector>
42 :
43 : /*
44 : when_any - Race multiple results tasks, select first success
45 : =============================================================
46 :
47 : OVERVIEW:
48 : ---------
49 : when_any launches N results-returning tasks concurrently. A task
50 : wins by returning !ec; errors and exceptions do not win. Once a
51 : winner is found, stop is requested for siblings and the winner's
52 : payload is returned. If no winner exists (all fail), one of the
53 : failures is surfaced (an error_code at variant index 0, or a child's
54 : exception rethrown); which one is unspecified.
55 :
56 : ARCHITECTURE:
57 : -------------
58 : The design mirrors when_all but with inverted completion semantics:
59 :
60 : when_all: complete when remaining_count reaches 0 (all done)
61 : when_any: complete when has_winner becomes true (first done)
62 : BUT still wait for remaining_count to reach 0 for cleanup
63 :
64 : Key components:
65 : - when_any_core: Shared state tracking winner and completion
66 : - when_any_results_runner: Wrapper coroutine for each child task
67 : - when_any_results_launcher/when_any_results_homogeneous_launcher:
68 : Awaitables that start all runners concurrently
69 :
70 : CRITICAL INVARIANTS:
71 : --------------------
72 : 1. Only a task returning !ec can become the winner (via atomic CAS)
73 : 2. All tasks must complete before parent resumes (cleanup safety)
74 : 3. Stop is requested immediately when winner is determined
75 : 4. Exceptions and errors do not claim winner status
76 :
77 : POSITIONAL VARIANT:
78 : -------------------
79 : The variadic overload returns std::variant<error_code, R1, R2, ..., Rn>.
80 : Index 0 is error_code (failure/no-winner). Index 1..N identifies the
81 : winning child and carries its payload.
82 :
83 : RANGE OVERLOAD:
84 : ---------------
85 : The range overload returns variant<error_code, pair<size_t, T>> for
86 : non-void children or variant<error_code, size_t> for void children.
87 :
88 : MEMORY MODEL:
89 : -------------
90 : Synchronization chain from winner's write to parent's read:
91 :
92 : 1. Winner thread writes result_ (non-atomic)
93 : 2. Winner thread calls signal_completion() -> fetch_sub(acq_rel) on remaining_count_
94 : 3. Last task thread (may be winner or non-winner) calls signal_completion()
95 : -> fetch_sub(acq_rel) on remaining_count_, observing count becomes 0
96 : 4. Last task returns caller_ex_.dispatch(continuation_) via symmetric transfer
97 : 5. Parent coroutine resumes and reads result_
98 :
99 : Synchronization analysis:
100 : - All fetch_sub operations on remaining_count_ form a release sequence
101 : - Winner's fetch_sub releases; subsequent fetch_sub operations participate
102 : in the modification order of remaining_count_
103 : - Last task's fetch_sub(acq_rel) synchronizes-with prior releases in the
104 : modification order, establishing happens-before from winner's writes
105 : - Executor dispatch() is expected to provide queue-based synchronization
106 : (release-on-post, acquire-on-execute) completing the chain to parent
107 : - Even inline executors work (same thread = sequenced-before)
108 :
109 : EXCEPTION SEMANTICS:
110 : --------------------
111 : Exceptions do NOT claim winner status. If a child throws, the exception
112 : is recorded but the combinator keeps waiting for a success. Only when
113 : all children complete without a winner is a failure surfaced. There is
114 : no priority between errors and exceptions, and no guarantee about which
115 : child's failure is reported: the result either returns an error_code at
116 : variant index 0 or rethrows a child's exception.
117 : */
118 :
119 : namespace boost {
120 : namespace capy {
121 :
122 : namespace detail {
123 :
124 : /** Core shared state for when_any operations.
125 :
126 : Contains all members and methods common to both heterogeneous (variadic)
127 : and homogeneous (range) when_any implementations. State classes embed
128 : this via composition to avoid CRTP destructor ordering issues.
129 :
130 : @par Thread Safety
131 : Atomic operations protect winner selection and completion count.
132 : */
133 : struct when_any_core
134 : {
135 : std::atomic<std::size_t> remaining_count_;
136 : std::size_t winner_index_{0};
137 : std::exception_ptr winner_exception_;
138 : std::stop_source stop_source_;
139 :
140 : // Bridges parent's stop token to our stop_source
141 : struct stop_callback_fn
142 : {
143 : std::stop_source* source_;
144 HIT 3 : void operator()() const noexcept
145 : {
146 : // Stopping can lose the last branch and destroy the join,
147 : // with its source, before the request returns; the copy
148 : // keeps the stop state alive until then.
149 3 : std::stop_source keep = *source_;
150 3 : keep.request_stop();
151 3 : }
152 : };
153 : using stop_callback_t = std::stop_callback<stop_callback_fn>;
154 : std::optional<stop_callback_t> parent_stop_callback_;
155 :
156 : continuation continuation_;
157 : await_context const* caller_env_ = nullptr;
158 :
159 : // Set when a branch is abandoned before finishing: the parent is
160 : // then abandoned rather than resumed.
161 : std::atomic<bool> lost_{false};
162 :
163 : /// Drop a share held by a runner that never finished.
164 8 : void lose_branch() noexcept
165 : {
166 8 : lost_.store(true, std::memory_order_relaxed);
167 8 : stop_source_.request_stop();
168 16 : if(remaining_count_.fetch_sub(1, std::memory_order_acq_rel) == 1)
169 : {
170 4 : auto parent = continuation_;
171 4 : capy::abandon(parent);
172 : }
173 8 : }
174 :
175 : // Placed last to avoid padding (1-byte atomic followed by 8-byte aligned members)
176 : std::atomic<bool> has_winner_{false};
177 :
178 52 : explicit when_any_core(std::size_t count) noexcept
179 52 : : remaining_count_(count)
180 : {
181 52 : }
182 :
183 : /** Atomically claim winner status; exactly one task succeeds. */
184 67 : bool try_win(std::size_t index) noexcept
185 : {
186 67 : bool expected = false;
187 67 : if(has_winner_.compare_exchange_strong(
188 : expected, true, std::memory_order_acq_rel))
189 : {
190 31 : winner_index_ = index;
191 31 : stop_source_.request_stop();
192 31 : return true;
193 : }
194 36 : return false;
195 : }
196 :
197 : /** @pre try_win() returned true. */
198 1 : void set_winner_exception(std::exception_ptr ep) noexcept
199 : {
200 1 : winner_exception_ = ep;
201 1 : }
202 :
203 : // Runners signal completion directly via final_suspend; no member function needed.
204 : };
205 :
206 : } // namespace detail
207 :
208 : namespace detail {
209 :
210 : // State for `results`-aware when_any: only !ec wins.
211 : template<typename... Ts>
212 : struct when_any_results_state
213 : {
214 : static constexpr std::size_t task_count = sizeof...(Ts);
215 : using variant_type = std::variant<std::error_code, Ts...>;
216 :
217 : when_any_core core_;
218 : std::optional<variant_type> result_;
219 : std::array<continuation, task_count> runner_handles_{};
220 :
221 : // A failure (error or exception) for the all-fail case. record_error
222 : // and record_exception overwrite each other, so which one survives is
223 : // unspecified (no priority between errors and exceptions).
224 : std::mutex failure_mu_;
225 : std::error_code last_error_;
226 : std::exception_ptr last_exception_;
227 :
228 32 : when_any_results_state()
229 32 : : core_(task_count)
230 : {
231 32 : }
232 :
233 16 : void record_error(std::error_code ec)
234 : {
235 16 : std::lock_guard lk(failure_mu_);
236 16 : last_error_ = ec;
237 16 : last_exception_ = nullptr;
238 16 : }
239 :
240 6 : void record_exception(std::exception_ptr ep)
241 : {
242 6 : std::lock_guard lk(failure_mu_);
243 6 : last_exception_ = ep;
244 6 : last_error_ = {};
245 6 : }
246 : };
247 :
248 : // Wrapper coroutine for `results`-aware when_any children.
249 : // unhandled_exception records the exception but does NOT claim winner status.
250 : template<typename StateType>
251 : struct when_any_results_runner
252 : {
253 : struct promise_type
254 : : detail::process_frame_mixin
255 : {
256 : StateType* state_ = nullptr;
257 : std::size_t index_ = 0;
258 : await_context env_;
259 : // Owns the branch's segment.
260 : chain_owner segment_;
261 : bool done_ = false;
262 :
263 124 : ~promise_type()
264 : {
265 124 : if(!done_ && state_)
266 8 : state_->core_.lose_branch();
267 124 : }
268 :
269 124 : when_any_results_runner get_return_object() noexcept
270 : {
271 : return when_any_results_runner(
272 124 : std::coroutine_handle<promise_type>::from_promise(*this));
273 : }
274 :
275 124 : std::suspend_always initial_suspend() noexcept { return {}; }
276 :
277 116 : auto final_suspend() noexcept
278 : {
279 : struct awaiter
280 : {
281 : promise_type* p_;
282 116 : bool await_ready() const noexcept { return false; }
283 116 : auto await_suspend(std::coroutine_handle<> h) noexcept
284 : {
285 116 : auto& core = p_->state_->core_;
286 116 : auto* counter = &core.remaining_count_;
287 116 : auto* lost = &core.lost_;
288 116 : auto* caller_env = core.caller_env_;
289 116 : auto& cont = core.continuation_;
290 :
291 116 : p_->done_ = true;
292 : // Resumed to unwind its abandoned branch: lost, not
293 : // finished. Stop is requested while this branch
294 : // still holds its share.
295 116 : if(p_->segment_.abandoned())
296 : {
297 14 : lost->store(true, std::memory_order_relaxed);
298 14 : core.stop_source_.request_stop();
299 : }
300 116 : h.destroy();
301 :
302 116 : auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel);
303 116 : if(remaining != 1)
304 68 : return detail::symmetric_transfer(std::noop_coroutine());
305 48 : if(lost->load(std::memory_order_relaxed))
306 : {
307 8 : auto parent = cont;
308 8 : capy::abandon(parent);
309 8 : return detail::symmetric_transfer(std::noop_coroutine());
310 : }
311 40 : return detail::symmetric_transfer(caller_env->executor.dispatch(cont));
312 : }
313 : void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed
314 : };
315 116 : return awaiter{this};
316 : }
317 :
318 104 : void return_void() noexcept {}
319 :
320 : // Exceptions do NOT win in `results` when_any
321 12 : void unhandled_exception() noexcept
322 : {
323 12 : state_->record_exception(std::current_exception());
324 12 : }
325 :
326 : // Not context_awaiter: a child whose await_suspend throws has
327 : // failed, and must reach unhandled_exception rather than terminate.
328 : template<class Awaitable>
329 : struct transform_awaiter
330 : {
331 : std::decay_t<Awaitable> a_;
332 : promise_type* p_;
333 :
334 118 : bool await_ready() { return a_.await_ready(); }
335 115 : decltype(auto) await_resume() { return a_.await_resume(); }
336 :
337 : template<class Promise>
338 117 : auto await_suspend(std::coroutine_handle<Promise> h)
339 : {
340 : using R = decltype(a_.await_suspend(h, &p_->env_));
341 : if constexpr (std::is_same_v<R, std::coroutine_handle<>>)
342 116 : return detail::symmetric_transfer(a_.await_suspend(h, &p_->env_));
343 : else
344 1 : return a_.await_suspend(h, &p_->env_);
345 : }
346 : };
347 :
348 : template<class Awaitable>
349 118 : auto await_transform(Awaitable&& a)
350 : {
351 : using A = std::decay_t<Awaitable>;
352 : if constexpr (ContextAwaitable<A>)
353 : {
354 : return transform_awaiter<Awaitable>{
355 118 : std::forward<Awaitable>(a), this};
356 : }
357 : else
358 : {
359 : static_assert(sizeof(A) == 0, "requires ContextAwaitable");
360 : }
361 : }
362 : };
363 :
364 : std::coroutine_handle<promise_type> h_;
365 :
366 124 : explicit when_any_results_runner(std::coroutine_handle<promise_type> h) noexcept
367 124 : : h_(h)
368 : {
369 124 : }
370 :
371 : when_any_results_runner(when_any_results_runner&& other) noexcept
372 : : h_(std::exchange(other.h_, nullptr))
373 : {
374 : }
375 :
376 : when_any_results_runner(when_any_results_runner const&) = delete;
377 : when_any_results_runner& operator=(when_any_results_runner const&) = delete;
378 : when_any_results_runner& operator=(when_any_results_runner&&) = delete;
379 :
380 124 : auto release() noexcept
381 : {
382 124 : return std::exchange(h_, nullptr);
383 : }
384 : };
385 :
386 : // Runner coroutine: only tries to win when the child returns !ec.
387 : template<std::size_t I, ContextAwaitable Awaitable, typename StateType>
388 : when_any_results_runner<StateType>
389 59 : make_when_any_results_runner(Awaitable* inner, StateType* state)
390 : {
391 : // Taken from the join's storage only once running, into a local:
392 : // a runner destroyed unstarted owns no branch, and one destroyed
393 : // unfinished destroys it before its promise reports the loss.
394 : Awaitable a(std::move(*inner));
395 : auto r = co_await abandonable<Awaitable>{a};
396 : if(!r)
397 : co_return;
398 : auto& result = *r;
399 :
400 : if(!std::get<0>(result))
401 : {
402 : // Success: try to claim winner
403 : if(state->core_.try_win(I))
404 : {
405 : try
406 : {
407 : state->result_.emplace(
408 : std::in_place_index<I + 1>,
409 : detail::extract_results_payload(std::move(result)));
410 : }
411 : catch(...)
412 : {
413 : state->core_.set_winner_exception(std::current_exception());
414 : }
415 : }
416 : }
417 : else
418 : {
419 : // Error: record but don't win
420 : state->record_error(std::get<0>(result));
421 : }
422 118 : }
423 :
424 : // Launcher for `results`-aware when_any.
425 : template<ContextAwaitable... Awaitables>
426 : class when_any_results_launcher
427 : {
428 : using state_type = when_any_results_state<
429 : results_payload_t<awaitable_result_t<Awaitables>>...>;
430 :
431 : std::tuple<Awaitables...>* tasks_;
432 : state_type* state_;
433 :
434 : public:
435 32 : when_any_results_launcher(
436 : std::tuple<Awaitables...>* tasks,
437 : state_type* state)
438 32 : : tasks_(tasks)
439 32 : , state_(state)
440 : {
441 32 : }
442 :
443 32 : bool await_ready() const noexcept
444 : {
445 32 : return sizeof...(Awaitables) == 0;
446 : }
447 :
448 32 : std::coroutine_handle<> await_suspend(
449 : std::coroutine_handle<> continuation, await_context const* caller_env)
450 : {
451 32 : state_->core_.continuation_.h = continuation;
452 32 : state_->core_.continuation_.owner = caller_env->owner;
453 32 : state_->core_.caller_env_ = caller_env;
454 :
455 32 : if(caller_env->stop_token.stop_possible())
456 : {
457 4 : state_->core_.parent_stop_callback_.emplace(
458 2 : caller_env->stop_token,
459 2 : when_any_core::stop_callback_fn{&state_->core_.stop_source_});
460 :
461 2 : if(caller_env->stop_token.stop_requested())
462 1 : state_->core_.stop_source_.request_stop();
463 : }
464 :
465 32 : auto token = state_->core_.stop_source_.get_token();
466 32 : launch_all(std::index_sequence_for<Awaitables...>{},
467 : caller_env->executor, token);
468 :
469 64 : return std::noop_coroutine();
470 32 : }
471 :
472 22 : void await_resume() const noexcept {}
473 :
474 : private:
475 : template<std::size_t... Is>
476 32 : void launch_all(std::index_sequence<Is...>,
477 : executor_ref ex, std::stop_token token)
478 : {
479 32 : (..., launch_one<Is>(ex, token));
480 32 : }
481 :
482 : template<std::size_t I>
483 59 : void launch_one(executor_ref caller_ex, std::stop_token token)
484 : {
485 59 : auto runner = make_when_any_results_runner<I>(
486 59 : &std::get<I>(*tasks_), state_);
487 :
488 59 : auto h = runner.release();
489 59 : h.promise().state_ = state_;
490 59 : h.promise().index_ = I;
491 59 : h.promise().segment_.bind(h, caller_ex);
492 59 : h.promise().env_ = await_context{caller_ex, token,
493 59 : state_->core_.caller_env_->frame_allocator,
494 118 : &h.promise().segment_};
495 :
496 59 : state_->runner_handles_[I].h = std::coroutine_handle<>{h};
497 59 : caller_ex.post(state_->runner_handles_[I]);
498 118 : }
499 : };
500 :
501 : /** Shared state for homogeneous `results`-aware when_any (range overload).
502 :
503 : @tparam T The payload type extracted from `results`.
504 : */
505 : template<typename T>
506 : struct when_any_results_homogeneous_state
507 : {
508 : when_any_core core_;
509 : std::optional<T> result_;
510 : std::unique_ptr<continuation[]> runner_handles_;
511 :
512 : std::mutex failure_mu_;
513 : std::error_code last_error_;
514 : std::exception_ptr last_exception_;
515 :
516 15 : explicit when_any_results_homogeneous_state(std::size_t count)
517 15 : : core_(count)
518 15 : , runner_handles_(std::make_unique<continuation[]>(count))
519 : {
520 15 : }
521 :
522 6 : void record_error(std::error_code ec)
523 : {
524 6 : std::lock_guard lk(failure_mu_);
525 6 : last_error_ = ec;
526 6 : last_exception_ = nullptr;
527 6 : }
528 :
529 4 : void record_exception(std::exception_ptr ep)
530 : {
531 4 : std::lock_guard lk(failure_mu_);
532 4 : last_exception_ = ep;
533 4 : last_error_ = {};
534 4 : }
535 : };
536 :
537 : /** Specialization for void `results` children (no payload storage). */
538 : template<>
539 : struct when_any_results_homogeneous_state<std::tuple<>>
540 : {
541 : when_any_core core_;
542 : std::unique_ptr<continuation[]> runner_handles_;
543 :
544 : std::mutex failure_mu_;
545 : std::error_code last_error_;
546 : std::exception_ptr last_exception_;
547 :
548 5 : explicit when_any_results_homogeneous_state(std::size_t count)
549 5 : : core_(count)
550 5 : , runner_handles_(std::make_unique<continuation[]>(count))
551 : {
552 5 : }
553 :
554 1 : void record_error(std::error_code ec)
555 : {
556 1 : std::lock_guard lk(failure_mu_);
557 1 : last_error_ = ec;
558 1 : last_exception_ = nullptr;
559 1 : }
560 :
561 2 : void record_exception(std::exception_ptr ep)
562 : {
563 2 : std::lock_guard lk(failure_mu_);
564 2 : last_exception_ = ep;
565 2 : last_error_ = {};
566 2 : }
567 : };
568 :
569 : /** Create a `results`-aware runner for homogeneous when_any (range path).
570 :
571 : Only tries to win when the child returns !ec.
572 : */
573 : template<ContextAwaitable Awaitable, typename StateType>
574 : when_any_results_runner<StateType>
575 65 : make_when_any_results_homogeneous_runner(
576 : Awaitable* inner, StateType* state, std::size_t index)
577 : {
578 : // Taken from the join's storage only once running, into a local:
579 : // a runner destroyed unstarted owns no branch, and one destroyed
580 : // unfinished destroys it before its promise reports the loss.
581 : Awaitable a(std::move(*inner));
582 : auto r = co_await abandonable<Awaitable>{a};
583 : if(!r)
584 : co_return;
585 : auto& result = *r;
586 :
587 : if(!std::get<0>(result))
588 : {
589 : if(state->core_.try_win(index))
590 : {
591 : using PayloadT = results_payload_t<
592 : awaitable_result_t<Awaitable>>;
593 : if constexpr (!std::is_same_v<PayloadT, std::tuple<>>)
594 : {
595 : try
596 : {
597 : state->result_.emplace(
598 : extract_results_payload(std::move(result)));
599 : }
600 : catch(...)
601 : {
602 : state->core_.set_winner_exception(
603 : std::current_exception());
604 : }
605 : }
606 : }
607 : }
608 : else
609 : {
610 : state->record_error(std::get<0>(result));
611 : }
612 130 : }
613 :
614 : /** Starts all `results`-aware homogeneous runners concurrently. */
615 : template<ContextAwaitableRange Range>
616 : class when_any_results_homogeneous_launcher
617 : {
618 : using Awaitable = std::ranges::range_value_t<Range>;
619 : using PayloadT = results_payload_t<awaitable_result_t<Awaitable>>;
620 :
621 : Range* range_;
622 : when_any_results_homogeneous_state<PayloadT>* state_;
623 :
624 : public:
625 20 : when_any_results_homogeneous_launcher(
626 : Range* range,
627 : when_any_results_homogeneous_state<PayloadT>* state)
628 20 : : range_(range)
629 20 : , state_(state)
630 : {
631 20 : }
632 :
633 20 : bool await_ready() const noexcept
634 : {
635 20 : return std::ranges::empty(*range_);
636 : }
637 :
638 20 : std::coroutine_handle<> await_suspend(
639 : std::coroutine_handle<> continuation, await_context const* caller_env)
640 : {
641 20 : state_->core_.continuation_.h = continuation;
642 20 : state_->core_.continuation_.owner = caller_env->owner;
643 20 : state_->core_.caller_env_ = caller_env;
644 :
645 20 : if(caller_env->stop_token.stop_possible())
646 : {
647 4 : state_->core_.parent_stop_callback_.emplace(
648 2 : caller_env->stop_token,
649 2 : when_any_core::stop_callback_fn{&state_->core_.stop_source_});
650 :
651 2 : if(caller_env->stop_token.stop_requested())
652 1 : state_->core_.stop_source_.request_stop();
653 : }
654 :
655 20 : auto token = state_->core_.stop_source_.get_token();
656 :
657 : // Phase 1: Create all runners without dispatching.
658 20 : std::size_t index = 0;
659 85 : for(auto&& a : *range_)
660 : {
661 65 : auto runner = make_when_any_results_homogeneous_runner(
662 : &a, state_, index);
663 :
664 65 : auto h = runner.release();
665 65 : h.promise().state_ = state_;
666 65 : h.promise().index_ = index;
667 65 : h.promise().segment_.bind(h, caller_env->executor);
668 65 : h.promise().env_ = await_context{caller_env->executor, token,
669 130 : caller_env->frame_allocator, &h.promise().segment_};
670 :
671 65 : state_->runner_handles_[index].h = std::coroutine_handle<>{h};
672 65 : ++index;
673 : }
674 :
675 : // Phase 2: Post all runners. Any may complete synchronously.
676 20 : auto* handles = state_->runner_handles_.get();
677 20 : std::size_t count = state_->core_.remaining_count_.load(std::memory_order_relaxed);
678 85 : for(std::size_t i = 0; i < count; ++i)
679 65 : caller_env->executor.post(handles[i]);
680 :
681 40 : return std::noop_coroutine();
682 85 : }
683 :
684 18 : void await_resume() const noexcept {}
685 : };
686 :
687 : } // namespace detail
688 :
689 : /** Asynchronously race a range of `results`-returning awaitables (non-void payloads).
690 :
691 : Only a child returning !ec can win. Errors and exceptions do not
692 : claim winner status. If all children fail, an unspecified one of
693 : the failures is reported — either an error_code at variant index 0,
694 : or a child's exception rethrown.
695 :
696 : @par Await-effects
697 :
698 : Takes ownership of the range, creates one wrapper coroutine per
699 : element, then posts every wrapper to the caller's executor. All
700 : children therefore run concurrently, each awaited with the caller's
701 : executor and frame allocator and with a stop token owned by this
702 : operation.
703 :
704 : Awaiting an empty range throws `std::invalid_argument` before any
705 : child is started.
706 :
707 : The first child to await-return a zero `ec` claims the win. Claiming
708 : the win requests stop on the operation's own stop token, which every
709 : sibling observes through the stop token it was awaited with. A child
710 : that await-returns a non-zero `ec`, or that exits via an exception,
711 : does not claim the win and does not request stop. The operation keeps
712 : waiting for a success. A stop request on the caller's stop token is
713 : also forwarded to every child.
714 :
715 : The await completes only after every child has finished, regardless of
716 : whether a win was claimed.
717 :
718 : @par Await-returns
719 : An object of type
720 : `std::variant<std::error_code, std::pair<std::size_t, PayloadT>>`,
721 : where `PayloadT` is the payload of one child's `results`. The
722 : payload of `results<T>` is `T`. The payload of any other
723 : `results<Ts...>` is `std::tuple<Ts...>`.
724 :
725 : @li Index 1 holds the winner's position in the input range paired
726 : with its payload.
727 : @li Index 0 holds a non-zero `error_code` when no child won, that is,
728 : when every child failed. It is the `ec` of one of the failed
729 : children; which one is unspecified.
730 :
731 : A child that succeeds after the win has already been claimed
732 : contributes nothing: its payload is discarded.
733 :
734 : If no child won and the failure selected for reporting is an
735 : exception rather than an `ec`, that exception is rethrown instead of
736 : await-returning. The choice of child is unspecified.
737 :
738 : @par Await-postcondition
739 : Every child has finished. If at least one child await-returned a zero
740 : `ec`, the result holds index 1. If producing the winner's payload
741 : threw, that exception is rethrown. Otherwise the result holds index 0,
742 : or a failed child's exception is rethrown.
743 :
744 : @par Remarks
745 : Cancellation follows the stop token of the caller's
746 : @ref await_context. A canceled child await-returns a non-zero `ec`
747 : and so cannot win. It does not decide the overall result, which the
748 : await-postcondition describes.
749 :
750 : @par Thread Safety
751 : The returned task must be awaited from a single execution context.
752 : Child awaitables execute concurrently but complete through the caller's
753 : executor.
754 :
755 : @par Exception Safety
756 : If extracting or move-constructing the winning payload throws, that
757 : exception is rethrown. In that case a winner was found, but its
758 : result could not be produced. If all children fail and the reported
759 : failure is an exception, that child's exception is rethrown (which
760 : child is unspecified).
761 :
762 : @throws std::invalid_argument From the await, if the range is empty.
763 :
764 : @note If a branch's coroutine is abandoned before it finishes,
765 : `when_any` requests stop on the remaining branches. Teardown
766 : of the branch's execution context is one such case. Once the
767 : last branch has finished or been abandoned, the awaiting
768 : parent is abandoned rather than resumed.
769 :
770 : @par Example
771 : @par !example example_1
772 :
773 :
774 : @param awaitables Range of `results`-returning awaitables (must
775 : not be empty).
776 : The task refers to the range until the await starts. If the
777 : range is a temporary and the task is awaited after the
778 : full-expression that created it, the behavior is undefined.
779 : A forward range whose elements are lvalues is copied, or moved
780 : when passed as an rvalue. The elements of any other range are
781 : moved into a vector. Copying an owning container of move-only
782 : elements, such as `std::vector<task<...>>`, is ill-formed, so
783 : pass it as an rvalue. A view such as `std::span` is copied and
784 : its elements are moved from, so their storage must remain valid
785 : until the await completes.
786 :
787 : @return A task yielding
788 : `std::variant<std::error_code, std::pair<std::size_t, PayloadT>>`.
789 :
790 : @see @ref ContextAwaitableRange, @ref when_any
791 : */
792 : template<ContextAwaitableRange R>
793 : requires detail::is_results_v<
794 : awaitable_result_t<std::ranges::range_value_t<R>>>
795 : && (!std::is_same_v<
796 : detail::results_payload_t<
797 : awaitable_result_t<std::ranges::range_value_t<R>>>,
798 : std::tuple<>>)
799 16 : [[nodiscard]] auto when_any(R&& awaitables)
800 : -> task<std::variant<std::error_code,
801 : std::pair<std::size_t,
802 : detail::results_payload_t<
803 : awaitable_result_t<std::ranges::range_value_t<R>>>>>>
804 : {
805 : using Awaitable = std::ranges::range_value_t<R>;
806 : using PayloadT = detail::results_payload_t<
807 : awaitable_result_t<Awaitable>>;
808 : using result_type = std::variant<std::error_code,
809 : std::pair<std::size_t, PayloadT>>;
810 : using OwnedRange = detail::owned_range_t<R>;
811 :
812 : auto count = std::ranges::size(awaitables);
813 : if(count == 0)
814 : throw std::invalid_argument("when_any requires at least one awaitable");
815 :
816 : OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
817 :
818 : detail::when_any_results_homogeneous_state<PayloadT> state(count);
819 :
820 : co_await detail::when_any_results_homogeneous_launcher<OwnedRange>(
821 : &owned_awaitables, &state);
822 :
823 : // Winner found
824 : if(state.core_.has_winner_.load(std::memory_order_acquire))
825 : {
826 : if(state.core_.winner_exception_)
827 : std::rethrow_exception(state.core_.winner_exception_);
828 : co_return result_type{std::in_place_index<1>,
829 : std::pair{state.core_.winner_index_, std::move(*state.result_)}};
830 : }
831 :
832 : // No winner — report the recorded failure
833 : if(state.last_exception_)
834 : std::rethrow_exception(state.last_exception_);
835 : co_return result_type{std::in_place_index<0>, state.last_error_};
836 32 : }
837 :
838 : /** Asynchronously race a range of void `results`-returning awaitables.
839 :
840 : Only a child returning !ec can win. Returns the winner's index
841 : at variant index 1, or error_code at index 0 on all-fail.
842 :
843 : @par Await-effects
844 :
845 : Takes ownership of the range, creates one wrapper coroutine per
846 : element, then posts every wrapper to the caller's executor. All
847 : children therefore run concurrently, each awaited with the caller's
848 : executor and frame allocator and with a stop token owned by this
849 : operation.
850 :
851 : Awaiting an empty range throws `std::invalid_argument` before any
852 : child is started.
853 :
854 : The first child to await-return a zero `ec` claims the win. Claiming
855 : the win requests stop on the operation's own stop token, which every
856 : sibling observes through the stop token it was awaited with. A child
857 : that await-returns a non-zero `ec`, or that exits via an exception,
858 : does not claim the win and does not request stop. The operation keeps
859 : waiting for a success. A stop request on the caller's stop token is
860 : also forwarded to every child.
861 :
862 : The await completes only after every child has finished, regardless of
863 : whether a win was claimed.
864 :
865 : @par Await-returns
866 : An object of type `std::variant<std::error_code, std::size_t>`.
867 :
868 : @li Index 1 holds the winner's position in the input range. The
869 : children have no payloads, so nothing else is reported.
870 : @li Index 0 holds a non-zero `error_code` when no child won, that is,
871 : when every child failed. It is the `ec` of one of the failed
872 : children; which one is unspecified.
873 :
874 : If no child won and the failure selected for reporting is an
875 : exception rather than an `ec`, that exception is rethrown instead of
876 : await-returning. The choice of child is unspecified.
877 :
878 : @par Await-postcondition
879 : Every child has finished. The result holds index 1 if at least one
880 : child await-returned a zero `ec`. Otherwise the result holds index 0,
881 : or a failed child's exception is rethrown.
882 :
883 : @par Remarks
884 : Cancellation follows the stop token of the caller's
885 : @ref await_context. A canceled child await-returns a non-zero `ec`
886 : and so cannot win. It does not decide the overall result, which the
887 : await-postcondition describes.
888 :
889 : @par Thread Safety
890 : The returned task must be awaited from a single execution context.
891 : Child awaitables execute concurrently but complete through the caller's
892 : executor.
893 :
894 : @par Exception Safety
895 : If all children fail and the reported failure is an exception,
896 : that child's exception is rethrown (which child is unspecified).
897 :
898 : @throws std::invalid_argument From the await, if the range is empty.
899 :
900 : @note If a branch's coroutine is abandoned before it finishes,
901 : `when_any` requests stop on the remaining branches. Teardown
902 : of the branch's execution context is one such case. Once the
903 : last branch has finished or been abandoned, the awaiting
904 : parent is abandoned rather than resumed.
905 :
906 : @par Example
907 : @par !example example_2
908 :
909 :
910 : @param awaitables Range of `results<>`-returning awaitables (must
911 : not be empty).
912 : The task refers to the range until the await starts. If the
913 : range is a temporary and the task is awaited after the
914 : full-expression that created it, the behavior is undefined.
915 : A forward range whose elements are lvalues is copied, or moved
916 : when passed as an rvalue. The elements of any other range are
917 : moved into a vector. Copying an owning container of move-only
918 : elements, such as `std::vector<task<...>>`, is ill-formed, so
919 : pass it as an rvalue. A view such as `std::span` is copied and
920 : its elements are moved from, so their storage must remain valid
921 : until the await completes.
922 :
923 : @return A task yielding `std::variant<std::error_code, std::size_t>`.
924 :
925 : @see @ref ContextAwaitableRange, @ref when_any
926 : */
927 : template<ContextAwaitableRange R>
928 : requires detail::is_results_v<
929 : awaitable_result_t<std::ranges::range_value_t<R>>>
930 : && std::is_same_v<
931 : detail::results_payload_t<
932 : awaitable_result_t<std::ranges::range_value_t<R>>>,
933 : std::tuple<>>
934 5 : [[nodiscard]] auto when_any(R&& awaitables)
935 : -> task<std::variant<std::error_code, std::size_t>>
936 : {
937 : using OwnedRange = detail::owned_range_t<R>;
938 : using result_type = std::variant<std::error_code, std::size_t>;
939 :
940 : auto count = std::ranges::size(awaitables);
941 : if(count == 0)
942 : throw std::invalid_argument("when_any requires at least one awaitable");
943 :
944 : OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
945 :
946 : detail::when_any_results_homogeneous_state<std::tuple<>> state(count);
947 :
948 : co_await detail::when_any_results_homogeneous_launcher<OwnedRange>(
949 : &owned_awaitables, &state);
950 :
951 : // Winner found
952 : if(state.core_.has_winner_.load(std::memory_order_acquire))
953 : {
954 : if(state.core_.winner_exception_)
955 : std::rethrow_exception(state.core_.winner_exception_);
956 : co_return result_type{std::in_place_index<1>,
957 : state.core_.winner_index_};
958 : }
959 :
960 : // No winner — report the recorded failure
961 : if(state.last_exception_)
962 : std::rethrow_exception(state.last_exception_);
963 : co_return result_type{std::in_place_index<0>, state.last_error_};
964 10 : }
965 :
966 : /** Asynchronously race `results`-returning awaitables, selecting the first success.
967 :
968 : Overload selected when all children return results<Ts...>.
969 : Only a child returning !ec can win. Errors and exceptions do
970 : not claim winner status.
971 :
972 : @par Await-effects
973 :
974 : Creates and posts one wrapper coroutine per argument to the caller's
975 : executor, in argument order. All children therefore run concurrently,
976 : each awaited with the caller's executor and frame allocator and with
977 : a stop token owned by this operation. The overload requires at least
978 : one awaitable, so there is no empty case.
979 :
980 : The first child to await-return a zero `ec` claims the win. Claiming
981 : the win requests stop on the operation's own stop token, which every
982 : sibling observes through the stop token it was awaited with. A child
983 : that await-returns a non-zero `ec`, or that exits via an exception,
984 : does not claim the win and does not request stop. The operation keeps
985 : waiting for a success. A stop request on the caller's stop token is
986 : also forwarded to every child.
987 :
988 : The await completes only after every child has finished, regardless of
989 : whether a win was claimed.
990 :
991 : @par Await-returns
992 : An object of type `std::variant<std::error_code, P1, ..., Pn>`, where
993 : `Pi` is the payload of the i-th child's `results`. The payload of
994 : `results<T>` is `T`. The payload of any other `results<Ts...>` is
995 : `std::tuple<Ts...>`.
996 :
997 : @li Index i+1 identifies the i-th argument as the winner and holds
998 : its payload.
999 : @li Index 0 holds a non-zero `error_code` when no child won, that is,
1000 : when every child failed. It is the `ec` of one of the failed
1001 : children; which one is unspecified.
1002 :
1003 : A child that succeeds after the win has already been claimed
1004 : contributes nothing: its payload is discarded.
1005 :
1006 : If no child won and the failure selected for reporting is an
1007 : exception rather than an `ec`, that exception is rethrown instead of
1008 : await-returning. The choice of child is unspecified.
1009 :
1010 : @par Await-postcondition
1011 : Every child has finished. If at least one child await-returned a zero
1012 : `ec`, the result holds the index of the winning child. If producing
1013 : the winner's payload threw, that exception is rethrown. Otherwise the
1014 : result holds index 0, or a failed child's exception is rethrown.
1015 :
1016 : @par Remarks
1017 : Cancellation follows the stop token of the caller's
1018 : @ref await_context. A canceled child await-returns a non-zero `ec`
1019 : and so cannot win. It does not decide the overall result, which the
1020 : await-postcondition describes.
1021 :
1022 : @par Thread Safety
1023 : The returned task must be awaited from a single execution context.
1024 : Child awaitables execute concurrently but complete through the caller's
1025 : executor.
1026 :
1027 : @par Exception Safety
1028 : If extracting or constructing the winning payload throws, that
1029 : exception is rethrown. In that case a winner was found, but its
1030 : result could not be produced. If all children fail and the reported
1031 : failure is an exception, that child's exception is rethrown (which
1032 : child is unspecified).
1033 :
1034 : @note A failing child does not cancel its siblings. `when_any`
1035 : keeps waiting until a child succeeds; the await completes
1036 : after every child has finished. To make a benign error (e.g.
1037 : `cond::canceled`) count as a win, wrap the child to translate
1038 : the error into success.
1039 :
1040 : @note If a branch's coroutine is abandoned before it finishes,
1041 : `when_any` requests stop on the remaining branches. Teardown
1042 : of the branch's execution context is one such case. Once the
1043 : last branch has finished or been abandoned, the awaiting
1044 : parent is abandoned rather than resumed.
1045 :
1046 : @par Example
1047 : @par !example example_3
1048 :
1049 : @param as The awaitables to race. Each must satisfy @ref
1050 : ContextAwaitable. The arguments are consumed when `when_any`
1051 : is called, not when the returned task is awaited.
1052 :
1053 : @return A task yielding `std::variant<std::error_code, P1, ..., Pn>`.
1054 :
1055 : @see @ref ContextAwaitable, @ref when_all
1056 : */
1057 : template<ContextAwaitable... As>
1058 : requires (sizeof...(As) > 0)
1059 : && detail::all_results_awaitables<As...>
1060 32 : [[nodiscard]] auto when_any(As... as)
1061 : -> task<std::variant<
1062 : std::error_code,
1063 : detail::results_payload_t<awaitable_result_t<As>>...>>
1064 : {
1065 : using result_type = std::variant<
1066 : std::error_code,
1067 : detail::results_payload_t<awaitable_result_t<As>>...>;
1068 :
1069 : detail::when_any_results_state<
1070 : detail::results_payload_t<awaitable_result_t<As>>...> state;
1071 : std::tuple<As...> awaitable_tuple(std::move(as)...);
1072 :
1073 : co_await detail::when_any_results_launcher<As...>(
1074 : &awaitable_tuple, &state);
1075 :
1076 : // Winner found: return their result
1077 : if(state.result_.has_value())
1078 : co_return std::move(*state.result_);
1079 :
1080 : // Winner claimed but payload construction failed
1081 : if(state.core_.winner_exception_)
1082 : std::rethrow_exception(state.core_.winner_exception_);
1083 :
1084 : // No winner — report the recorded failure
1085 : if(state.last_exception_)
1086 : std::rethrow_exception(state.last_exception_);
1087 : co_return result_type{std::in_place_index<0>, state.last_error_};
1088 64 : }
1089 :
1090 : } // namespace capy
1091 : } // namespace boost
1092 :
1093 : #endif
|