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 : /** 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`.
722 :
723 : @li Index 1 holds the winner's position in the input range paired
724 : with its payload.
725 : @li Index 0 holds a non-zero `error_code` when no child won, that is,
726 : when every child failed. It is the `ec` of one of the failed
727 : children; which one is unspecified.
728 :
729 : A child that succeeds after the win has already been claimed
730 : contributes nothing: its payload is discarded.
731 :
732 : If no child won and the failure selected for reporting is an
733 : exception rather than an `ec`, that exception is rethrown instead of
734 : await-returning. The choice of child is unspecified.
735 :
736 : @par Await-postcondition
737 : Every child has finished. If at least one child await-returned a zero
738 : `ec`, the result holds index 1. If producing the winner's payload
739 : threw, that exception is rethrown. Otherwise the result holds index 0,
740 : or a failed child's exception is rethrown.
741 :
742 : @par Remarks
743 : Supports _ContextAwaitable cancellation_. A canceled child await-returns a
744 : non-zero `ec` and so cannot win; if no child has already succeeded,
745 : the result settles at index 0.
746 :
747 : @par Thread Safety
748 : The returned task must be awaited from a single execution context.
749 : Child awaitables execute concurrently but complete through the caller's
750 : executor.
751 :
752 : @param awaitables Range of `results`-returning awaitables (must
753 : not be empty).
754 :
755 : @return A task yielding variant<error_code, pair<size_t, PayloadT>>
756 : where index 0 is failure and index 1 carries the winner's
757 : index and payload.
758 :
759 : @throws std::invalid_argument if range is empty.
760 :
761 : @par Exception Safety
762 : The winner's exception is rethrown if extracting or
763 : move-constructing the winning payload throws. In that case a winner
764 : was found, but its result could not be produced. If all children
765 : fail and the reported failure is an exception, that child's
766 : exception is rethrown (which child is unspecified).
767 :
768 : @note If a branch's coroutine is abandoned before it finishes, for
769 : example by teardown of its execution context, `when_any`
770 : requests stop on the remaining branches, and the awaiting
771 : parent is abandoned rather than resumed once the last branch
772 : has finished or been abandoned.
773 :
774 : @par Example
775 : @par !example example_1
776 :
777 :
778 : @see @ref ContextAwaitableRange, @ref when_any
779 : */
780 : template<ContextAwaitableRange R>
781 : requires detail::is_results_v<
782 : awaitable_result_t<std::ranges::range_value_t<R>>>
783 : && (!std::is_same_v<
784 : detail::results_payload_t<
785 : awaitable_result_t<std::ranges::range_value_t<R>>>,
786 : std::tuple<>>)
787 16 : [[nodiscard]] auto when_any(R&& awaitables)
788 : -> task<std::variant<std::error_code,
789 : std::pair<std::size_t,
790 : detail::results_payload_t<
791 : awaitable_result_t<std::ranges::range_value_t<R>>>>>>
792 : {
793 : using Awaitable = std::ranges::range_value_t<R>;
794 : using PayloadT = detail::results_payload_t<
795 : awaitable_result_t<Awaitable>>;
796 : using result_type = std::variant<std::error_code,
797 : std::pair<std::size_t, PayloadT>>;
798 : using OwnedRange = detail::owned_range_t<R>;
799 :
800 : auto count = std::ranges::size(awaitables);
801 : if(count == 0)
802 : throw std::invalid_argument("when_any requires at least one awaitable");
803 :
804 : OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
805 :
806 : detail::when_any_results_homogeneous_state<PayloadT> state(count);
807 :
808 : co_await detail::when_any_results_homogeneous_launcher<OwnedRange>(
809 : &owned_awaitables, &state);
810 :
811 : // Winner found
812 : if(state.core_.has_winner_.load(std::memory_order_acquire))
813 : {
814 : if(state.core_.winner_exception_)
815 : std::rethrow_exception(state.core_.winner_exception_);
816 : co_return result_type{std::in_place_index<1>,
817 : std::pair{state.core_.winner_index_, std::move(*state.result_)}};
818 : }
819 :
820 : // No winner — report the recorded failure
821 : if(state.last_exception_)
822 : std::rethrow_exception(state.last_exception_);
823 : co_return result_type{std::in_place_index<0>, state.last_error_};
824 32 : }
825 :
826 : /** Race a range of void `results`-returning awaitables.
827 :
828 : Only a child returning !ec can win. Returns the winner's index
829 : at variant index 1, or error_code at index 0 on all-fail.
830 :
831 : @par Await-effects
832 :
833 : Takes ownership of the range, creates one wrapper coroutine per
834 : element, then posts every wrapper to the caller's executor. All
835 : children therefore run concurrently, each awaited with the caller's
836 : executor and frame allocator and with a stop token owned by this
837 : operation.
838 :
839 : Awaiting an empty range throws `std::invalid_argument` before any
840 : child is started.
841 :
842 : The first child to await-return a zero `ec` claims the win. Claiming
843 : the win requests stop on the operation's own stop token, which every
844 : sibling observes through the stop token it was awaited with. A child
845 : that await-returns a non-zero `ec`, or that exits via an exception,
846 : does not claim the win and does not request stop. The operation keeps
847 : waiting for a success. A stop request on the caller's stop token is
848 : also forwarded to every child.
849 :
850 : The await completes only after every child has finished, regardless of
851 : whether a win was claimed.
852 :
853 : @par Await-returns
854 : An object of type `std::variant<std::error_code, std::size_t>`.
855 :
856 : @li Index 1 holds the winner's position in the input range. The
857 : children have no payloads, so nothing else is reported.
858 : @li Index 0 holds a non-zero `error_code` when no child won, that is,
859 : when every child failed. It is the `ec` of one of the failed
860 : children; which one is unspecified.
861 :
862 : If no child won and the failure selected for reporting is an
863 : exception rather than an `ec`, that exception is rethrown instead of
864 : await-returning. The choice of child is unspecified.
865 :
866 : @par Await-postcondition
867 : Every child has finished. The result holds index 1 if at least one
868 : child await-returned a zero `ec`. Otherwise the result holds index 0,
869 : or a failed child's exception is rethrown.
870 :
871 : @par Remarks
872 : Supports _ContextAwaitable cancellation_. A canceled child await-returns a
873 : non-zero `ec` and so cannot win; if no child has already succeeded,
874 : the result settles at index 0.
875 :
876 : @par Thread Safety
877 : The returned task must be awaited from a single execution context.
878 : Child awaitables execute concurrently but complete through the caller's
879 : executor.
880 :
881 : @param awaitables Range of `results<>`-returning awaitables (must
882 : not be empty).
883 :
884 : @return A task yielding variant<error_code, size_t> where index 0
885 : is failure and index 1 carries the winner's index.
886 :
887 : @throws std::invalid_argument if range is empty.
888 :
889 : @par Exception Safety
890 : If all children fail and the reported failure is an exception,
891 : that child's exception is rethrown (which child is unspecified).
892 :
893 : @note If a branch's coroutine is abandoned before it finishes, for
894 : example by teardown of its execution context, `when_any`
895 : requests stop on the remaining branches, and the awaiting
896 : parent is abandoned rather than resumed once the last branch
897 : has finished or been abandoned.
898 :
899 : @par Example
900 : @par !example example_2
901 :
902 :
903 : @see @ref ContextAwaitableRange, @ref when_any
904 : */
905 : template<ContextAwaitableRange R>
906 : requires detail::is_results_v<
907 : awaitable_result_t<std::ranges::range_value_t<R>>>
908 : && std::is_same_v<
909 : detail::results_payload_t<
910 : awaitable_result_t<std::ranges::range_value_t<R>>>,
911 : std::tuple<>>
912 5 : [[nodiscard]] auto when_any(R&& awaitables)
913 : -> task<std::variant<std::error_code, std::size_t>>
914 : {
915 : using OwnedRange = detail::owned_range_t<R>;
916 : using result_type = std::variant<std::error_code, std::size_t>;
917 :
918 : auto count = std::ranges::size(awaitables);
919 : if(count == 0)
920 : throw std::invalid_argument("when_any requires at least one awaitable");
921 :
922 : OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
923 :
924 : detail::when_any_results_homogeneous_state<std::tuple<>> state(count);
925 :
926 : co_await detail::when_any_results_homogeneous_launcher<OwnedRange>(
927 : &owned_awaitables, &state);
928 :
929 : // Winner found
930 : if(state.core_.has_winner_.load(std::memory_order_acquire))
931 : {
932 : if(state.core_.winner_exception_)
933 : std::rethrow_exception(state.core_.winner_exception_);
934 : co_return result_type{std::in_place_index<1>,
935 : state.core_.winner_index_};
936 : }
937 :
938 : // No winner — report the recorded failure
939 : if(state.last_exception_)
940 : std::rethrow_exception(state.last_exception_);
941 : co_return result_type{std::in_place_index<0>, state.last_error_};
942 10 : }
943 :
944 : /** Race `results`-returning awaitables, selecting the first success.
945 :
946 : Overload selected when all children return results<Ts...>.
947 : Only a child returning !ec can win. Errors and exceptions do
948 : not claim winner status.
949 :
950 : @par Await-effects
951 :
952 : Creates and posts one wrapper coroutine per argument to the caller's
953 : executor, in argument order. All children therefore run concurrently,
954 : each awaited with the caller's executor and frame allocator and with
955 : a stop token owned by this operation. The overload requires at least
956 : one awaitable, so there is no empty case.
957 :
958 : The first child to await-return a zero `ec` claims the win. Claiming
959 : the win requests stop on the operation's own stop token, which every
960 : sibling observes through the stop token it was awaited with. A child
961 : that await-returns a non-zero `ec`, or that exits via an exception,
962 : does not claim the win and does not request stop. The operation keeps
963 : waiting for a success. A stop request on the caller's stop token is
964 : also forwarded to every child.
965 :
966 : The await completes only after every child has finished, regardless of
967 : whether a win was claimed.
968 :
969 : @par Await-returns
970 : An object of type `std::variant<std::error_code, P1, ..., Pn>`, where
971 : `Pi` is the payload of the i-th child's `results`.
972 :
973 : @li Index i+1 identifies the i-th argument as the winner and holds
974 : its payload.
975 : @li Index 0 holds a non-zero `error_code` when no child won, that is,
976 : when every child failed. It is the `ec` of one of the failed
977 : children; which one is unspecified.
978 :
979 : A child that succeeds after the win has already been claimed
980 : contributes nothing: its payload is discarded.
981 :
982 : If no child won and the failure selected for reporting is an
983 : exception rather than an `ec`, that exception is rethrown instead of
984 : await-returning. The choice of child is unspecified.
985 :
986 : @par Await-postcondition
987 : Every child has finished. If at least one child await-returned a zero
988 : `ec`, the result holds the index of the winning child. If producing
989 : the winner's payload threw, that exception is rethrown. Otherwise the
990 : result holds index 0, or a failed child's exception is rethrown.
991 :
992 : @par Remarks
993 : Supports _ContextAwaitable cancellation_. A canceled child await-returns a
994 : non-zero `ec` and so cannot win; if no child has already succeeded,
995 : the result settles at index 0.
996 :
997 : @par Thread Safety
998 : The returned task must be awaited from a single execution context.
999 : Child awaitables execute concurrently but complete through the caller's
1000 : executor.
1001 :
1002 : @param as The awaitables to race. Each must satisfy @ref
1003 : ContextAwaitable and is consumed (moved-from) when `when_any`
1004 : is awaited.
1005 :
1006 : @return A task yielding variant<error_code, R1, ..., Rn> where
1007 : index 0 is the failure/no-winner case and index i+1
1008 : identifies the winning child. On all-fail, index 0 holds
1009 : an error_code from one of the failed children (unspecified
1010 : which; no priority between errors and exceptions).
1011 :
1012 : @par Exception Safety
1013 : The winner's exception is rethrown if extracting or constructing
1014 : the winning payload throws. In that case a winner was found, but
1015 : its result could not be produced. If all children fail and the
1016 : reported failure is an exception, that child's exception is
1017 : rethrown (which child is unspecified).
1018 :
1019 : @note A failing child does not cancel its siblings; `when_any`
1020 : waits for a success or for every child to finish. To make a
1021 : benign error (e.g. @c cond::canceled) count as a win, wrap
1022 : the child to translate the error into success. See the
1023 : Concurrent Composition tutorial.
1024 :
1025 : @note If a branch's coroutine is abandoned before it finishes, for
1026 : example by teardown of its execution context, `when_any`
1027 : requests stop on the remaining branches, and the awaiting
1028 : parent is abandoned rather than resumed once the last branch
1029 : has finished or been abandoned.
1030 : */
1031 : template<ContextAwaitable... As>
1032 : requires (sizeof...(As) > 0)
1033 : && detail::all_results_awaitables<As...>
1034 32 : [[nodiscard]] auto when_any(As... as)
1035 : -> task<std::variant<
1036 : std::error_code,
1037 : detail::results_payload_t<awaitable_result_t<As>>...>>
1038 : {
1039 : using result_type = std::variant<
1040 : std::error_code,
1041 : detail::results_payload_t<awaitable_result_t<As>>...>;
1042 :
1043 : detail::when_any_results_state<
1044 : detail::results_payload_t<awaitable_result_t<As>>...> state;
1045 : std::tuple<As...> awaitable_tuple(std::move(as)...);
1046 :
1047 : co_await detail::when_any_results_launcher<As...>(
1048 : &awaitable_tuple, &state);
1049 :
1050 : // Winner found: return their result
1051 : if(state.result_.has_value())
1052 : co_return std::move(*state.result_);
1053 :
1054 : // Winner claimed but payload construction failed
1055 : if(state.core_.winner_exception_)
1056 : std::rethrow_exception(state.core_.winner_exception_);
1057 :
1058 : // No winner — report the recorded failure
1059 : if(state.last_exception_)
1060 : std::rethrow_exception(state.last_exception_);
1061 : co_return result_type{std::in_place_index<0>, state.last_error_};
1062 64 : }
1063 :
1064 : } // namespace capy
1065 : } // namespace boost
1066 :
1067 : #endif
|