TLA Line data 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_WHEN_ALL_HPP
12 : #define BOOST_CAPY_WHEN_ALL_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/abandon.hpp>
21 : #include <boost/capy/detail/owned_range.hpp>
22 : #include <boost/capy/ex/frame_alloc_mixin.hpp>
23 : #include <boost/capy/ex/await_context.hpp>
24 : #include <boost/capy/ex/frame_allocator.hpp>
25 : #include <boost/capy/task.hpp>
26 :
27 : #include <array>
28 : #include <atomic>
29 : #include <exception>
30 : #include <memory>
31 : #include <optional>
32 : #include <ranges>
33 : #include <stdexcept>
34 : #include <stop_token>
35 : #include <tuple>
36 : #include <type_traits>
37 : #include <utility>
38 : #include <vector>
39 :
40 : namespace boost {
41 : namespace capy {
42 :
43 : namespace detail {
44 :
45 : /** Holds the result of a single task within when_all.
46 : */
47 : template<typename T>
48 : struct result_holder
49 : {
50 : std::optional<T> value_;
51 :
52 HIT 122 : void set(T v)
53 : {
54 122 : value_ = std::move(v);
55 122 : }
56 :
57 105 : T get() &&
58 : {
59 105 : return std::move(*value_);
60 : }
61 : };
62 :
63 : /** Core shared state for when_all operations.
64 :
65 : Contains all members and methods common to both heterogeneous (variadic)
66 : and homogeneous (range) when_all implementations. State classes embed
67 : this via composition to avoid CRTP destructor ordering issues.
68 :
69 : @par Thread Safety
70 : Atomic operations protect exception capture and completion count.
71 : */
72 : struct when_all_core
73 : {
74 : std::atomic<std::size_t> remaining_count_;
75 :
76 : // Exception storage - first error wins, others discarded
77 : std::atomic<bool> has_exception_{false};
78 : std::exception_ptr first_exception_;
79 :
80 : std::stop_source stop_source_;
81 :
82 : // Bridges parent's stop token to our stop_source
83 : struct stop_callback_fn
84 : {
85 : std::stop_source* source_;
86 4 : void operator()() const
87 : {
88 : // Stopping can lose the last branch and destroy the join,
89 : // with its source, before the request returns; the copy
90 : // keeps the stop state alive until then.
91 4 : std::stop_source keep = *source_;
92 4 : keep.request_stop();
93 4 : }
94 : };
95 : using stop_callback_t = std::stop_callback<stop_callback_fn>;
96 : std::optional<stop_callback_t> parent_stop_callback_;
97 :
98 : continuation continuation_;
99 : await_context const* caller_env_ = nullptr;
100 :
101 : // Set when a branch is abandoned before finishing: the parent is
102 : // then abandoned rather than resumed.
103 : std::atomic<bool> lost_{false};
104 :
105 : /// Drop a share held by a runner that never finished.
106 8 : void lose_branch() noexcept
107 : {
108 8 : lost_.store(true, std::memory_order_relaxed);
109 8 : stop_source_.request_stop();
110 16 : if(remaining_count_.fetch_sub(1, std::memory_order_acq_rel) == 1)
111 : {
112 4 : auto parent = continuation_;
113 4 : capy::abandon(parent);
114 : }
115 8 : }
116 :
117 98 : explicit when_all_core(std::size_t count) noexcept
118 98 : : remaining_count_(count)
119 : {
120 98 : }
121 :
122 : /** Capture an exception (first one wins). */
123 20 : void capture_exception(std::exception_ptr ep)
124 : {
125 20 : bool expected = false;
126 20 : if(has_exception_.compare_exchange_strong(
127 : expected, true, std::memory_order_relaxed))
128 19 : first_exception_ = ep;
129 20 : }
130 : };
131 :
132 : /** Shared state for heterogeneous when_all (variadic overload).
133 :
134 : @tparam Ts The result types of the tasks.
135 : */
136 : template<typename... Ts>
137 : struct when_all_state
138 : {
139 : static constexpr std::size_t task_count = sizeof...(Ts);
140 :
141 : when_all_core core_;
142 : std::tuple<result_holder<Ts>...> results_;
143 : std::array<continuation, task_count> runner_handles_{};
144 :
145 : std::atomic<bool> has_error_{false};
146 : std::error_code first_error_;
147 :
148 78 : when_all_state()
149 78 : : core_(task_count)
150 : {
151 78 : }
152 :
153 : /** Record the first error (subsequent errors are discarded). */
154 46 : void record_error(std::error_code ec)
155 : {
156 46 : bool expected = false;
157 46 : if(has_error_.compare_exchange_strong(
158 : expected, true, std::memory_order_relaxed))
159 32 : first_error_ = ec;
160 46 : }
161 : };
162 :
163 : /** Shared state for homogeneous when_all (range overload).
164 :
165 : Stores extracted results payloads in a vector indexed by task
166 : position. Tracks the first error_code for error propagation.
167 :
168 : @tparam T The payload type extracted from `results`.
169 : */
170 : template<typename T>
171 : struct when_all_homogeneous_state
172 : {
173 : when_all_core core_;
174 : std::vector<std::optional<T>> results_;
175 : std::unique_ptr<continuation[]> runner_handles_;
176 :
177 : std::atomic<bool> has_error_{false};
178 : std::error_code first_error_;
179 :
180 15 : explicit when_all_homogeneous_state(std::size_t count)
181 15 : : core_(count)
182 30 : , results_(count)
183 15 : , runner_handles_(std::make_unique<continuation[]>(count))
184 : {
185 15 : }
186 :
187 27 : void set_result(std::size_t index, T value)
188 : {
189 27 : results_[index].emplace(std::move(value));
190 27 : }
191 :
192 : /** Record the first error (subsequent errors are discarded). */
193 7 : void record_error(std::error_code ec)
194 : {
195 7 : bool expected = false;
196 7 : if(has_error_.compare_exchange_strong(
197 : expected, true, std::memory_order_relaxed))
198 5 : first_error_ = ec;
199 7 : }
200 : };
201 :
202 : /** Specialization for void `results` children (no payload storage). */
203 : template<>
204 : struct when_all_homogeneous_state<std::tuple<>>
205 : {
206 : when_all_core core_;
207 : std::unique_ptr<continuation[]> runner_handles_;
208 :
209 : std::atomic<bool> has_error_{false};
210 : std::error_code first_error_;
211 :
212 5 : explicit when_all_homogeneous_state(std::size_t count)
213 5 : : core_(count)
214 5 : , runner_handles_(std::make_unique<continuation[]>(count))
215 : {
216 5 : }
217 :
218 : /** Record the first error (subsequent errors are discarded). */
219 1 : void record_error(std::error_code ec)
220 : {
221 1 : bool expected = false;
222 1 : if(has_error_.compare_exchange_strong(
223 : expected, true, std::memory_order_relaxed))
224 1 : first_error_ = ec;
225 1 : }
226 : };
227 :
228 : /** Wrapper coroutine that intercepts task completion for when_all.
229 :
230 : Parameterized on StateType to work with both heterogeneous (variadic)
231 : and homogeneous (range) state types. All state types expose their
232 : shared members through a `core_` member of type when_all_core.
233 :
234 : @tparam StateType The state type (when_all_state or when_all_homogeneous_state).
235 : */
236 : template<typename StateType>
237 : struct when_all_runner
238 : {
239 : struct promise_type
240 : : detail::process_frame_mixin
241 : {
242 : StateType* state_ = nullptr;
243 : std::size_t index_ = 0;
244 : await_context env_;
245 : // Owns the branch's segment.
246 : chain_owner segment_;
247 : bool done_ = false;
248 :
249 209 : ~promise_type()
250 : {
251 209 : if(!done_ && state_)
252 8 : state_->core_.lose_branch();
253 209 : }
254 :
255 209 : when_all_runner get_return_object() noexcept
256 : {
257 : return when_all_runner(
258 209 : std::coroutine_handle<promise_type>::from_promise(*this));
259 : }
260 :
261 209 : std::suspend_always initial_suspend() noexcept
262 : {
263 209 : return {};
264 : }
265 :
266 201 : auto final_suspend() noexcept
267 : {
268 : struct awaiter
269 : {
270 : promise_type* p_;
271 201 : bool await_ready() const noexcept { return false; }
272 201 : auto await_suspend(std::coroutine_handle<> h) noexcept
273 : {
274 201 : auto& core = p_->state_->core_;
275 201 : auto* counter = &core.remaining_count_;
276 201 : auto* lost = &core.lost_;
277 201 : auto* caller_env = core.caller_env_;
278 201 : auto& cont = core.continuation_;
279 :
280 201 : p_->done_ = true;
281 : // Resumed to unwind its abandoned branch: lost, not
282 : // finished. Stop is requested while this branch
283 : // still holds its share.
284 201 : if(p_->segment_.abandoned())
285 : {
286 19 : lost->store(true, std::memory_order_relaxed);
287 19 : core.stop_source_.request_stop();
288 : }
289 201 : h.destroy();
290 :
291 201 : auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel);
292 201 : if(remaining != 1)
293 107 : return detail::symmetric_transfer(std::noop_coroutine());
294 94 : if(lost->load(std::memory_order_relaxed))
295 : {
296 10 : auto parent = cont;
297 10 : capy::abandon(parent);
298 10 : return detail::symmetric_transfer(std::noop_coroutine());
299 : }
300 84 : return detail::symmetric_transfer(caller_env->executor.dispatch(cont));
301 : }
302 : void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed
303 : };
304 201 : return awaiter{this};
305 : }
306 :
307 181 : void return_void() noexcept {}
308 :
309 20 : void unhandled_exception() noexcept
310 : {
311 20 : state_->core_.capture_exception(std::current_exception());
312 20 : state_->core_.stop_source_.request_stop();
313 20 : }
314 :
315 : // Not context_awaiter: a child whose await_suspend throws has
316 : // failed, and must reach unhandled_exception rather than terminate.
317 : template<class Awaitable>
318 : struct transform_awaiter
319 : {
320 : std::decay_t<Awaitable> a_;
321 : promise_type* p_;
322 :
323 203 : bool await_ready() { return a_.await_ready(); }
324 200 : decltype(auto) await_resume() { return a_.await_resume(); }
325 :
326 : template<class Promise>
327 203 : auto await_suspend(std::coroutine_handle<Promise> h)
328 : {
329 : using R = decltype(a_.await_suspend(h, &p_->env_));
330 : if constexpr (std::is_same_v<R, std::coroutine_handle<>>)
331 202 : return detail::symmetric_transfer(a_.await_suspend(h, &p_->env_));
332 : else
333 1 : return a_.await_suspend(h, &p_->env_);
334 : }
335 : };
336 :
337 : template<class Awaitable>
338 203 : auto await_transform(Awaitable&& a)
339 : {
340 : using A = std::decay_t<Awaitable>;
341 : if constexpr (ContextAwaitable<A>)
342 : {
343 : return transform_awaiter<Awaitable>{
344 203 : std::forward<Awaitable>(a), this};
345 : }
346 : else
347 : {
348 : static_assert(sizeof(A) == 0, "requires ContextAwaitable");
349 : }
350 : }
351 : };
352 :
353 : std::coroutine_handle<promise_type> h_;
354 :
355 209 : explicit when_all_runner(std::coroutine_handle<promise_type> h) noexcept
356 209 : : h_(h)
357 : {
358 209 : }
359 :
360 : // Enable move for all clang versions - some versions need it
361 : when_all_runner(when_all_runner&& other) noexcept
362 : : h_(std::exchange(other.h_, nullptr))
363 : {
364 : }
365 :
366 : when_all_runner(when_all_runner const&) = delete;
367 : when_all_runner& operator=(when_all_runner const&) = delete;
368 : when_all_runner& operator=(when_all_runner&&) = delete;
369 :
370 209 : auto release() noexcept
371 : {
372 209 : return std::exchange(h_, nullptr);
373 : }
374 : };
375 :
376 : /** Create a `results`-aware runner for a single awaitable (range path).
377 :
378 : Checks the error code, records errors and requests stop on failure,
379 : or extracts the payload on success.
380 : */
381 : template<ContextAwaitable Awaitable, typename StateType>
382 : when_all_runner<StateType>
383 48 : make_when_all_homogeneous_runner(Awaitable* inner, StateType* state, std::size_t index)
384 : {
385 : // Taken from the join's storage only once running, into a local:
386 : // a runner destroyed unstarted owns no branch, and one destroyed
387 : // unfinished destroys it before its promise reports the loss.
388 : Awaitable a(std::move(*inner));
389 : auto r = co_await abandonable<Awaitable>{a};
390 : if(!r)
391 : co_return;
392 : auto& result = *r;
393 :
394 : if(std::get<0>(result))
395 : {
396 : state->record_error(std::get<0>(result));
397 : state->core_.stop_source_.request_stop();
398 : }
399 : else
400 : {
401 : using PayloadT = results_payload_t<
402 : awaitable_result_t<Awaitable>>;
403 : if constexpr (!std::is_same_v<PayloadT, std::tuple<>>)
404 : {
405 : state->set_result(index,
406 : extract_results_payload(std::move(result)));
407 : }
408 : }
409 96 : }
410 :
411 : /** Create a runner for `results` children that requests stop on ec. */
412 : template<std::size_t Index, ContextAwaitable Awaitable, typename... Ts>
413 : when_all_runner<when_all_state<Ts...>>
414 161 : make_when_all_results_runner(Awaitable* inner, when_all_state<Ts...>* state)
415 : {
416 : // Taken from the join's storage only once running, into a local:
417 : // a runner destroyed unstarted owns no branch, and one destroyed
418 : // unfinished destroys it before its promise reports the loss.
419 : Awaitable a(std::move(*inner));
420 : auto r = co_await abandonable<Awaitable>{a};
421 : if(!r)
422 : co_return;
423 : auto ec = std::get<0>(*r);
424 : std::get<Index>(state->results_).set(std::move(*r));
425 :
426 : if(ec)
427 : {
428 : state->record_error(ec);
429 : state->core_.stop_source_.request_stop();
430 : }
431 322 : }
432 :
433 : /** Launcher that uses `results`-aware runners. */
434 : template<ContextAwaitable... Awaitables>
435 : class when_all_results_launcher
436 : {
437 : using state_type = when_all_state<awaitable_result_t<Awaitables>...>;
438 :
439 : std::tuple<Awaitables...>* awaitables_;
440 : state_type* state_;
441 :
442 : public:
443 78 : when_all_results_launcher(
444 : std::tuple<Awaitables...>* awaitables,
445 : state_type* state)
446 78 : : awaitables_(awaitables)
447 78 : , state_(state)
448 : {
449 78 : }
450 :
451 78 : bool await_ready() const noexcept
452 : {
453 78 : return sizeof...(Awaitables) == 0;
454 : }
455 :
456 78 : std::coroutine_handle<> await_suspend(
457 : std::coroutine_handle<> continuation, await_context const* caller_env)
458 : {
459 78 : state_->core_.continuation_.h = continuation;
460 78 : state_->core_.continuation_.owner = caller_env->owner;
461 78 : state_->core_.caller_env_ = caller_env;
462 :
463 78 : if(caller_env->stop_token.stop_possible())
464 : {
465 6 : state_->core_.parent_stop_callback_.emplace(
466 3 : caller_env->stop_token,
467 3 : when_all_core::stop_callback_fn{&state_->core_.stop_source_});
468 :
469 3 : if(caller_env->stop_token.stop_requested())
470 1 : state_->core_.stop_source_.request_stop();
471 : }
472 :
473 78 : auto token = state_->core_.stop_source_.get_token();
474 78 : launch_all(std::index_sequence_for<Awaitables...>{},
475 : caller_env->executor, token);
476 :
477 156 : return std::noop_coroutine();
478 78 : }
479 :
480 66 : void await_resume() const noexcept {}
481 :
482 : private:
483 : template<std::size_t... Is>
484 78 : void launch_all(std::index_sequence<Is...>,
485 : executor_ref ex, std::stop_token token)
486 : {
487 78 : (..., launch_one<Is>(ex, token));
488 78 : }
489 :
490 : template<std::size_t I>
491 161 : void launch_one(executor_ref caller_ex, std::stop_token token)
492 : {
493 161 : auto runner = make_when_all_results_runner<I>(
494 161 : &std::get<I>(*awaitables_), state_);
495 :
496 161 : auto h = runner.release();
497 161 : h.promise().state_ = state_;
498 161 : h.promise().segment_.bind(h, caller_ex);
499 161 : h.promise().env_ = await_context{caller_ex, token,
500 161 : state_->core_.caller_env_->frame_allocator,
501 322 : &h.promise().segment_};
502 :
503 161 : state_->runner_handles_[I].h = std::coroutine_handle<>{h};
504 161 : state_->core_.caller_env_->executor.post(state_->runner_handles_[I]);
505 322 : }
506 : };
507 :
508 : /** Helper to extract a single result from state.
509 : This is a separate function to work around a GCC-11 ICE that occurs
510 : when using nested immediately-invoked lambdas with pack expansion.
511 : */
512 : template<std::size_t I, typename... Ts>
513 105 : auto extract_single_result(when_all_state<Ts...>& state)
514 : {
515 105 : return std::move(std::get<I>(state.results_)).get();
516 : }
517 :
518 : /** Extract all results from state as a tuple.
519 : */
520 : template<typename... Ts>
521 50 : auto extract_results(when_all_state<Ts...>& state)
522 : {
523 82 : return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
524 : // Explicit element types: CTAD would collapse a single
525 : // `results` child via the tuple copy deduction guide
526 : return std::tuple<
527 : decltype(extract_single_result<Is>(state))...>(
528 50 : extract_single_result<Is>(state)...);
529 100 : }(std::index_sequence_for<Ts...>{});
530 : }
531 :
532 : /** Starts all homogeneous runners concurrently.
533 :
534 : Two-phase approach: create all runners first, then post all.
535 : This avoids lifetime issues if a task completes synchronously.
536 : */
537 : template<typename Range>
538 : class when_all_homogeneous_launcher
539 : {
540 : using Awaitable = std::ranges::range_value_t<Range>;
541 : using PayloadT = results_payload_t<awaitable_result_t<Awaitable>>;
542 :
543 : Range* range_;
544 : when_all_homogeneous_state<PayloadT>* state_;
545 :
546 : public:
547 20 : when_all_homogeneous_launcher(
548 : Range* range,
549 : when_all_homogeneous_state<PayloadT>* state)
550 20 : : range_(range)
551 20 : , state_(state)
552 : {
553 20 : }
554 :
555 20 : bool await_ready() const noexcept
556 : {
557 20 : return std::ranges::empty(*range_);
558 : }
559 :
560 20 : std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation, await_context const* caller_env)
561 : {
562 20 : state_->core_.continuation_.h = continuation;
563 20 : state_->core_.continuation_.owner = caller_env->owner;
564 20 : state_->core_.caller_env_ = caller_env;
565 :
566 20 : if(caller_env->stop_token.stop_possible())
567 : {
568 4 : state_->core_.parent_stop_callback_.emplace(
569 2 : caller_env->stop_token,
570 2 : when_all_core::stop_callback_fn{&state_->core_.stop_source_});
571 :
572 2 : if(caller_env->stop_token.stop_requested())
573 1 : state_->core_.stop_source_.request_stop();
574 : }
575 :
576 20 : auto token = state_->core_.stop_source_.get_token();
577 :
578 : // Phase 1: Create all runners without dispatching.
579 20 : std::size_t index = 0;
580 68 : for(auto&& a : *range_)
581 : {
582 48 : auto runner = make_when_all_homogeneous_runner(
583 : &a, state_, index);
584 :
585 48 : auto h = runner.release();
586 48 : h.promise().state_ = state_;
587 48 : h.promise().index_ = index;
588 48 : h.promise().segment_.bind(h, caller_env->executor);
589 48 : h.promise().env_ = await_context{caller_env->executor, token,
590 96 : caller_env->frame_allocator, &h.promise().segment_};
591 :
592 48 : state_->runner_handles_[index].h = std::coroutine_handle<>{h};
593 48 : ++index;
594 : }
595 :
596 : // Phase 2: Post all runners. Any may complete synchronously.
597 : // After last post, state_ and this may be destroyed.
598 20 : auto* handles = state_->runner_handles_.get();
599 20 : std::size_t count = state_->core_.remaining_count_.load(std::memory_order_relaxed);
600 68 : for(std::size_t i = 0; i < count; ++i)
601 48 : caller_env->executor.post(handles[i]);
602 :
603 40 : return std::noop_coroutine();
604 68 : }
605 :
606 18 : void await_resume() const noexcept
607 : {
608 18 : }
609 : };
610 :
611 : } // namespace detail
612 :
613 : /** Execute a range of `results`-returning awaitables concurrently.
614 :
615 : Starts all awaitables simultaneously and waits for all to complete.
616 : On success, extracted payloads are collected in a vector preserving
617 : input order. The first error_code makes a stop request that every
618 : sibling observes, and is propagated in the outer results.
619 : Exceptions always beat error codes.
620 :
621 : @li All child awaitables run concurrently on the caller's executor.
622 : @li Payloads are returned as a vector in input order.
623 : @li First error_code wins and makes a stop request that siblings observe.
624 : @li Exception always beats error_code.
625 : @li Completes only after all children have finished.
626 :
627 : @par Await-effects
628 :
629 : Takes ownership of the range, creates one wrapper coroutine per
630 : element, then posts every wrapper to the caller's executor. All
631 : children therefore run concurrently, each awaited with the caller's
632 : executor and frame allocator and with a stop token owned by this
633 : operation.
634 :
635 : Awaiting an empty range throws `std::invalid_argument` before any
636 : child is started.
637 :
638 : A stop request is made on the operation's own stop token when:
639 :
640 : @li a child await-returns a non-zero `ec`, or
641 : @li a child exits via an exception, or
642 : @li the caller's stop token is triggered.
643 :
644 : Every sibling observes that request through the stop token it was
645 : awaited with. The request does not end the operation: the await
646 : completes only after every child has finished.
647 :
648 : @par Await-returns
649 : An object of type `results<std::vector<PayloadT>>` destructuring as
650 : `[ec, values]`, where `PayloadT` is the payload of one child's
651 : `results`.
652 :
653 : `ec` is the first non-zero `ec` await-returned by a child, in
654 : completion order rather than input order. The `ec` of every other
655 : child is discarded.
656 :
657 : On success, `values` holds one payload per element of the input
658 : range, in input order. If `ec` is set, `values` is empty: the
659 : payloads of the children that did succeed are discarded.
660 :
661 : If any child exits via an exception, the first such exception is
662 : rethrown instead of await-returning, even when a child also reported
663 : an `ec`.
664 :
665 : @par Await-postcondition
666 : Every child has finished. `ec` is success only if every child
667 : await-returned success. If `ec` is success, `values` holds one
668 : payload per input awaitable; otherwise `values` is empty.
669 :
670 : @par Remarks
671 : Supports _ContextAwaitable cancellation_.
672 :
673 : @par Thread Safety
674 : The returned task must be awaited from a single execution context.
675 : Child awaitables execute concurrently but complete through the caller's
676 : executor.
677 :
678 : @param awaitables Range of `results`-returning awaitables to execute
679 : concurrently (must not be empty).
680 :
681 : @return A task yielding `results<vector<PayloadT>>` where PayloadT
682 : is the payload extracted from each child's results.
683 :
684 : @throws std::invalid_argument if range is empty (thrown before
685 : coroutine suspends).
686 :
687 : @par Exception Safety
688 : If a child throws, the first child exception is rethrown after
689 : all children complete (exception beats error_code).
690 :
691 : @note If a branch's coroutine is abandoned before it finishes, for
692 : example by teardown of its execution context, `when_all`
693 : requests stop on the remaining branches, and the awaiting
694 : parent is abandoned rather than resumed once the last branch
695 : has finished or been abandoned.
696 :
697 : @par Example
698 : @par !example example_1
699 :
700 :
701 : @see @ref ContextAwaitableRange, @ref when_all
702 : */
703 : template<ContextAwaitableRange R>
704 : requires detail::is_results_v<
705 : awaitable_result_t<std::ranges::range_value_t<R>>>
706 : && (!std::is_same_v<
707 : detail::results_payload_t<
708 : awaitable_result_t<std::ranges::range_value_t<R>>>,
709 : std::tuple<>>)
710 17 : [[nodiscard]] auto when_all(R&& awaitables)
711 : -> task<results<std::vector<
712 : detail::results_payload_t<
713 : awaitable_result_t<std::ranges::range_value_t<R>>>>>>
714 : {
715 : using Awaitable = std::ranges::range_value_t<R>;
716 : using PayloadT = detail::results_payload_t<
717 : awaitable_result_t<Awaitable>>;
718 : using OwnedRange = detail::owned_range_t<R>;
719 :
720 : auto count = std::ranges::size(awaitables);
721 : if(count == 0)
722 : throw std::invalid_argument("when_all requires at least one awaitable");
723 :
724 : OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
725 :
726 : detail::when_all_homogeneous_state<PayloadT> state(count);
727 :
728 : co_await detail::when_all_homogeneous_launcher<OwnedRange>(
729 : &owned_awaitables, &state);
730 :
731 : if(state.core_.first_exception_)
732 : std::rethrow_exception(state.core_.first_exception_);
733 :
734 : if(state.has_error_.load(std::memory_order_relaxed))
735 : co_return results<std::vector<PayloadT>>{state.first_error_, {}};
736 :
737 : std::vector<PayloadT> values;
738 : values.reserve(count);
739 : for(auto& opt : state.results_)
740 : values.push_back(std::move(*opt));
741 :
742 : co_return results<std::vector<PayloadT>>{std::error_code(), std::move(values)};
743 34 : }
744 :
745 : /** Execute a range of void `results`-returning awaitables concurrently.
746 :
747 : Starts all awaitables simultaneously and waits for all to complete.
748 : Since all awaitables return results<>, no payload values are
749 : collected. The first error_code makes a stop request that every
750 : sibling observes, and is propagated. Exceptions always beat error
751 : codes.
752 :
753 : @par Await-effects
754 :
755 : Takes ownership of the range, creates one wrapper coroutine per
756 : element, then posts every wrapper to the caller's executor. All
757 : children therefore run concurrently, each awaited with the caller's
758 : executor and frame allocator and with a stop token owned by this
759 : operation.
760 :
761 : Awaiting an empty range throws `std::invalid_argument` before any
762 : child is started.
763 :
764 : A stop request is made on the operation's own stop token when:
765 :
766 : @li a child await-returns a non-zero `ec`, or
767 : @li a child exits via an exception, or
768 : @li the caller's stop token is triggered.
769 :
770 : Every sibling observes that request through the stop token it was
771 : awaited with. The request does not end the operation: the await
772 : completes only after every child has finished.
773 :
774 : @par Await-returns
775 : An object of type `results<>` destructuring as `[ec]`. The children
776 : have no payloads, so nothing else is reported.
777 :
778 : `ec` is the first non-zero `ec` await-returned by a child, in
779 : completion order rather than input order. The `ec` of every other
780 : child is discarded.
781 :
782 : If any child exits via an exception, the first such exception is
783 : rethrown instead of await-returning, even when a child also reported
784 : an `ec`.
785 :
786 : @par Await-postcondition
787 : Every child has finished. `ec` is success only if every child
788 : await-returned success.
789 :
790 : @par Remarks
791 : Supports _ContextAwaitable cancellation_.
792 :
793 : @par Thread Safety
794 : The returned task must be awaited from a single execution context.
795 : Child awaitables execute concurrently but complete through the caller's
796 : executor.
797 :
798 : @param awaitables Range of `results<>`-returning awaitables to
799 : execute concurrently (must not be empty).
800 :
801 : @return A task yielding `results<>` whose ec is the first child
802 : error, or default-constructed on success.
803 :
804 : @throws std::invalid_argument if range is empty.
805 :
806 : @par Exception Safety
807 : If a child throws, the first child exception is rethrown after
808 : all children complete (exception beats error_code).
809 :
810 : @note If a branch's coroutine is abandoned before it finishes, for
811 : example by teardown of its execution context, `when_all`
812 : requests stop on the remaining branches, and the awaiting
813 : parent is abandoned rather than resumed once the last branch
814 : has finished or been abandoned.
815 :
816 : @par Example
817 : @par !example example_2
818 :
819 :
820 : @see @ref ContextAwaitableRange, @ref when_all
821 : */
822 : template<ContextAwaitableRange R>
823 : requires detail::is_results_v<
824 : awaitable_result_t<std::ranges::range_value_t<R>>>
825 : && std::is_same_v<
826 : detail::results_payload_t<
827 : awaitable_result_t<std::ranges::range_value_t<R>>>,
828 : std::tuple<>>
829 6 : [[nodiscard]] auto when_all(R&& awaitables) -> task<results<>>
830 : {
831 : using OwnedRange = detail::owned_range_t<R>;
832 :
833 : auto count = std::ranges::size(awaitables);
834 : if(count == 0)
835 : throw std::invalid_argument("when_all requires at least one awaitable");
836 :
837 : OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
838 :
839 : detail::when_all_homogeneous_state<std::tuple<>> state(count);
840 :
841 : co_await detail::when_all_homogeneous_launcher<OwnedRange>(
842 : &owned_awaitables, &state);
843 :
844 : if(state.core_.first_exception_)
845 : std::rethrow_exception(state.core_.first_exception_);
846 :
847 : if(state.has_error_.load(std::memory_order_relaxed))
848 : co_return results<>{state.first_error_};
849 :
850 : co_return results<>{};
851 12 : }
852 :
853 : /** Execute `results`-returning awaitables concurrently, inspecting error codes.
854 :
855 : Overload selected when all children return results<Ts...>.
856 : The error_code is lifted out of each child into a single outer
857 : results. On success all values are returned; on failure the
858 : first error_code wins.
859 :
860 : @par Await-effects
861 :
862 : Creates and posts one wrapper coroutine per argument to the caller's
863 : executor, in argument order. All children therefore run concurrently,
864 : each awaited with the caller's executor and frame allocator and with
865 : a stop token owned by this operation. The overload requires at least
866 : one awaitable, so there is no empty case.
867 :
868 : A stop request is made on the operation's own stop token when:
869 :
870 : @li a child await-returns a non-zero `ec`, or
871 : @li a child exits via an exception, or
872 : @li the caller's stop token is triggered.
873 :
874 : Every sibling observes that request through the stop token it was
875 : awaited with. The request does not end the operation: the await
876 : completes only after every child has finished.
877 :
878 : @par Await-returns
879 : An object of type `results<P1, ..., Pn>` destructuring as
880 : `[ec, v1, ..., vn]`, where `Pi` is the payload of the i-th child's
881 : `results`.
882 :
883 : `ec` is the first non-zero `ec` await-returned by a child, in
884 : completion order rather than argument order. The `ec` of every other
885 : child is discarded.
886 :
887 : Each `vi` is the payload the i-th child itself await-returned, even
888 : when that child or a sibling reported an `ec`. A failed child
889 : therefore still contributes whatever payload it produced. This
890 : differs from the range overloads, which discard all payloads once any
891 : child fails.
892 :
893 : If any child exits via an exception, the first such exception is
894 : rethrown instead of await-returning, even when a child also reported
895 : an `ec`.
896 :
897 : @par Await-postcondition
898 : Every child has finished. Each `vi` holds the i-th child's payload,
899 : and `ec` is success only if every child await-returned success.
900 :
901 : @par Remarks
902 : Supports _ContextAwaitable cancellation_.
903 :
904 : @par Thread Safety
905 : The returned task must be awaited from a single execution context.
906 : Child awaitables execute concurrently but complete through the caller's
907 : executor.
908 :
909 : @par Exception Safety
910 : If a child throws, the first child exception is rethrown after
911 : all children complete (exception beats error_code).
912 :
913 : @note If a branch's coroutine is abandoned before it finishes, for
914 : example by teardown of its execution context, `when_all`
915 : requests stop on the remaining branches, and the awaiting
916 : parent is abandoned rather than resumed once the last branch
917 : has finished or been abandoned.
918 :
919 : @param awaitables One or more awaitables each returning
920 : results<Ts...>.
921 :
922 : @return A task yielding `results<R1, R2, ..., Rn>` where each Ri
923 : follows the payload flattening rules.
924 : */
925 : template<ContextAwaitable... As>
926 : requires (sizeof...(As) > 0)
927 : && detail::all_results_awaitables<As...>
928 78 : [[nodiscard]] auto when_all(As... awaitables)
929 : -> task<results<
930 : detail::results_payload_t<awaitable_result_t<As>>...>>
931 : {
932 : using result_type = results<
933 : detail::results_payload_t<awaitable_result_t<As>>...>;
934 :
935 : detail::when_all_state<awaitable_result_t<As>...> state;
936 : std::tuple<As...> awaitable_tuple(std::move(awaitables)...);
937 :
938 : co_await detail::when_all_results_launcher<As...>(&awaitable_tuple, &state);
939 :
940 : // Exception always wins over error_code
941 : if(state.core_.first_exception_)
942 : std::rethrow_exception(state.core_.first_exception_);
943 :
944 : auto r = detail::build_when_all_results<result_type>(
945 : detail::extract_results(state));
946 : if(state.has_error_.load(std::memory_order_relaxed))
947 : std::get<0>(r) = state.first_error_;
948 : co_return r;
949 156 : }
950 :
951 : } // namespace capy
952 : } // namespace boost
953 :
954 : #endif
|