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 173 : void set(T v)
53 : {
54 173 : value_ = std::move(v);
55 173 : }
56 :
57 156 : T get() &&
58 : {
59 156 : 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 115 : explicit when_all_core(std::size_t count) noexcept
118 115 : : remaining_count_(count)
119 : {
120 115 : }
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 95 : when_all_state()
149 95 : : core_(task_count)
150 : {
151 95 : }
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 260 : ~promise_type()
250 : {
251 260 : if(!done_ && state_)
252 8 : state_->core_.lose_branch();
253 260 : }
254 :
255 260 : when_all_runner get_return_object() noexcept
256 : {
257 : return when_all_runner(
258 260 : std::coroutine_handle<promise_type>::from_promise(*this));
259 : }
260 :
261 260 : std::suspend_always initial_suspend() noexcept
262 : {
263 260 : return {};
264 : }
265 :
266 252 : auto final_suspend() noexcept
267 : {
268 : struct awaiter
269 : {
270 : promise_type* p_;
271 252 : bool await_ready() const noexcept { return false; }
272 252 : auto await_suspend(std::coroutine_handle<> h) noexcept
273 : {
274 252 : auto& core = p_->state_->core_;
275 252 : auto* counter = &core.remaining_count_;
276 252 : auto* lost = &core.lost_;
277 252 : auto* caller_env = core.caller_env_;
278 252 : auto& cont = core.continuation_;
279 :
280 252 : 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 252 : if(p_->segment_.abandoned())
285 : {
286 19 : lost->store(true, std::memory_order_relaxed);
287 19 : core.stop_source_.request_stop();
288 : }
289 252 : h.destroy();
290 :
291 252 : auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel);
292 252 : if(remaining != 1)
293 141 : return detail::symmetric_transfer(std::noop_coroutine());
294 111 : 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 101 : 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 252 : return awaiter{this};
305 : }
306 :
307 232 : 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 254 : bool await_ready() { return a_.await_ready(); }
324 251 : decltype(auto) await_resume() { return a_.await_resume(); }
325 :
326 : template<class Promise>
327 254 : 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 253 : 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 254 : 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 254 : 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 260 : explicit when_all_runner(std::coroutine_handle<promise_type> h) noexcept
356 260 : : h_(h)
357 : {
358 260 : }
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 260 : auto release() noexcept
371 : {
372 260 : 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 212 : 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 424 : }
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 95 : when_all_results_launcher(
444 : std::tuple<Awaitables...>* awaitables,
445 : state_type* state)
446 95 : : awaitables_(awaitables)
447 95 : , state_(state)
448 : {
449 95 : }
450 :
451 95 : bool await_ready() const noexcept
452 : {
453 95 : return sizeof...(Awaitables) == 0;
454 : }
455 :
456 95 : std::coroutine_handle<> await_suspend(
457 : std::coroutine_handle<> continuation, await_context const* caller_env)
458 : {
459 95 : state_->core_.continuation_.h = continuation;
460 95 : state_->core_.continuation_.owner = caller_env->owner;
461 95 : state_->core_.caller_env_ = caller_env;
462 :
463 95 : 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 95 : auto token = state_->core_.stop_source_.get_token();
474 95 : launch_all(std::index_sequence_for<Awaitables...>{},
475 : caller_env->executor, token);
476 :
477 190 : return std::noop_coroutine();
478 95 : }
479 :
480 83 : void await_resume() const noexcept {}
481 :
482 : private:
483 : template<std::size_t... Is>
484 95 : void launch_all(std::index_sequence<Is...>,
485 : executor_ref ex, std::stop_token token)
486 : {
487 95 : (..., launch_one<Is>(ex, token));
488 95 : }
489 :
490 : template<std::size_t I>
491 212 : void launch_one(executor_ref caller_ex, std::stop_token token)
492 : {
493 212 : auto runner = make_when_all_results_runner<I>(
494 212 : &std::get<I>(*awaitables_), state_);
495 :
496 212 : auto h = runner.release();
497 212 : h.promise().state_ = state_;
498 212 : h.promise().segment_.bind(h, caller_ex);
499 212 : h.promise().env_ = await_context{caller_ex, token,
500 212 : state_->core_.caller_env_->frame_allocator,
501 424 : &h.promise().segment_};
502 :
503 212 : state_->runner_handles_[I].h = std::coroutine_handle<>{h};
504 212 : state_->core_.caller_env_->executor.post(state_->runner_handles_[I]);
505 424 : }
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 156 : auto extract_single_result(when_all_state<Ts...>& state)
514 : {
515 156 : 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 67 : auto extract_results(when_all_state<Ts...>& state)
522 : {
523 99 : 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 67 : extract_single_result<Is>(state)...);
529 134 : }(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 : /** Asynchronously execute a range of `results`-returning awaitables concurrently.
614 :
615 : Posts every awaitable to the caller's executor, in input order, and
616 : waits for all to complete. The executor decides the order they start.
617 : On success, extracted payloads are collected in a vector preserving
618 : input order. The first error_code makes a stop request that every
619 : sibling observes, and is propagated in the outer results.
620 : Exceptions always beat error codes.
621 :
622 : @li All child awaitables run concurrently on the caller's executor.
623 : @li Payloads are returned as a vector in input order.
624 : @li First error_code wins and makes a stop request that siblings observe.
625 : @li Exception always beats error_code.
626 : @li Completes only after all children have finished.
627 :
628 : @par Await-effects
629 :
630 : Takes ownership of the range, creates one wrapper coroutine per
631 : element, then posts every wrapper to the caller's executor. All
632 : children therefore run concurrently, each awaited with the caller's
633 : executor and frame allocator and with a stop token owned by this
634 : operation.
635 :
636 : Awaiting an empty range throws `std::invalid_argument` before any
637 : child is started.
638 :
639 : A stop request is made on the operation's own stop token when:
640 :
641 : @li a child await-returns a non-zero `ec`, or
642 : @li a child exits via an exception, or
643 : @li the caller's stop token is triggered.
644 :
645 : Every sibling observes that request through the stop token it was
646 : awaited with. The request does not end the operation: the await
647 : completes only after every child has finished.
648 :
649 : @par Await-returns
650 : An object of type `results<std::vector<PayloadT>>` destructuring as
651 : `[ec, values]`, where `PayloadT` is the payload of one child's
652 : `results`. The payload of `results<T>` is `T`. The payload of any
653 : other `results<Ts...>` is `std::tuple<Ts...>`.
654 :
655 : `ec` is the first non-zero `ec` await-returned by a child, in
656 : completion order rather than input order. The `ec` of every other
657 : child is discarded.
658 :
659 : On success, `values` holds one payload per element of the input
660 : range, in input order. If `ec` is set, `values` is empty: the
661 : payloads of the children that did succeed are discarded.
662 :
663 : If any child exits via an exception, the first such exception is
664 : rethrown instead of await-returning, even when a child also reported
665 : an `ec`.
666 :
667 : @par Await-postcondition
668 : Every child has finished. `ec` is success only if every child
669 : await-returned success. If `ec` is success, `values` holds one
670 : payload per input awaitable; otherwise `values` is empty.
671 :
672 : @par Remarks
673 : Cancellation follows the stop token of the caller's
674 : @ref await_context.
675 :
676 : @par Thread Safety
677 : The returned task must be awaited from a single execution context.
678 : Child awaitables execute concurrently but complete through the caller's
679 : executor.
680 :
681 : @par Exception Safety
682 : If a child throws, the first child exception is rethrown after
683 : all children complete (exception beats error_code).
684 :
685 : @throws std::invalid_argument From the await, if the range is empty.
686 :
687 : @note If a branch's coroutine is abandoned before it finishes,
688 : `when_all` requests stop on the remaining branches. Teardown
689 : of the branch's execution context is one such case. Once the
690 : last branch has finished or been abandoned, the awaiting
691 : parent is abandoned rather than resumed.
692 :
693 : @par Example
694 : @par !example example_1
695 :
696 :
697 : @param awaitables Range of `results`-returning awaitables to execute
698 : concurrently (must not be empty).
699 : The task refers to the range until the await starts. If the
700 : range is a temporary and the task is awaited after the
701 : full-expression that created it, the behavior is undefined.
702 : A forward range whose elements are lvalues is copied, or moved
703 : when passed as an rvalue. The elements of any other range are
704 : moved into a vector. Copying an owning container of move-only
705 : elements, such as `std::vector<task<...>>`, is ill-formed, so
706 : pass it as an rvalue. A view such as `std::span` is copied and
707 : its elements are moved from, so their storage must remain valid
708 : until the await completes.
709 :
710 : @return A task yielding `results<std::vector<PayloadT>>`.
711 :
712 : @see @ref ContextAwaitableRange, @ref when_all
713 : */
714 : template<ContextAwaitableRange R>
715 : requires detail::is_results_v<
716 : awaitable_result_t<std::ranges::range_value_t<R>>>
717 : && (!std::is_same_v<
718 : detail::results_payload_t<
719 : awaitable_result_t<std::ranges::range_value_t<R>>>,
720 : std::tuple<>>)
721 17 : [[nodiscard]] auto when_all(R&& awaitables)
722 : -> task<results<std::vector<
723 : detail::results_payload_t<
724 : awaitable_result_t<std::ranges::range_value_t<R>>>>>>
725 : {
726 : using Awaitable = std::ranges::range_value_t<R>;
727 : using PayloadT = detail::results_payload_t<
728 : awaitable_result_t<Awaitable>>;
729 : using OwnedRange = detail::owned_range_t<R>;
730 :
731 : auto count = std::ranges::size(awaitables);
732 : if(count == 0)
733 : throw std::invalid_argument("when_all requires at least one awaitable");
734 :
735 : OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
736 :
737 : detail::when_all_homogeneous_state<PayloadT> state(count);
738 :
739 : co_await detail::when_all_homogeneous_launcher<OwnedRange>(
740 : &owned_awaitables, &state);
741 :
742 : if(state.core_.first_exception_)
743 : std::rethrow_exception(state.core_.first_exception_);
744 :
745 : if(state.has_error_.load(std::memory_order_relaxed))
746 : co_return results<std::vector<PayloadT>>{state.first_error_, {}};
747 :
748 : std::vector<PayloadT> values;
749 : values.reserve(count);
750 : for(auto& opt : state.results_)
751 : values.push_back(std::move(*opt));
752 :
753 : co_return results<std::vector<PayloadT>>{std::error_code(), std::move(values)};
754 34 : }
755 :
756 : /** Asynchronously execute a range of void `results`-returning awaitables concurrently.
757 :
758 : Posts every awaitable to the caller's executor, in input order, and
759 : waits for all to complete. The executor decides the order they start.
760 : Since all awaitables return results<>, no payload values are
761 : collected. The first error_code makes a stop request that every
762 : sibling observes, and is propagated. Exceptions always beat error
763 : codes.
764 :
765 : @par Await-effects
766 :
767 : Takes ownership of the range, creates one wrapper coroutine per
768 : element, then posts every wrapper to the caller's executor. All
769 : children therefore run concurrently, each awaited with the caller's
770 : executor and frame allocator and with a stop token owned by this
771 : operation.
772 :
773 : Awaiting an empty range throws `std::invalid_argument` before any
774 : child is started.
775 :
776 : A stop request is made on the operation's own stop token when:
777 :
778 : @li a child await-returns a non-zero `ec`, or
779 : @li a child exits via an exception, or
780 : @li the caller's stop token is triggered.
781 :
782 : Every sibling observes that request through the stop token it was
783 : awaited with. The request does not end the operation: the await
784 : completes only after every child has finished.
785 :
786 : @par Await-returns
787 : An object of type `results<>` destructuring as `[ec]`. The children
788 : have no payloads, so nothing else is reported.
789 :
790 : `ec` is the first non-zero `ec` await-returned by a child, in
791 : completion order rather than input order. The `ec` of every other
792 : child is discarded.
793 :
794 : If any child exits via an exception, the first such exception is
795 : rethrown instead of await-returning, even when a child also reported
796 : an `ec`.
797 :
798 : @par Await-postcondition
799 : Every child has finished. `ec` is success only if every child
800 : await-returned success.
801 :
802 : @par Remarks
803 : Cancellation follows the stop token of the caller's
804 : @ref await_context.
805 :
806 : @par Thread Safety
807 : The returned task must be awaited from a single execution context.
808 : Child awaitables execute concurrently but complete through the caller's
809 : executor.
810 :
811 : @par Exception Safety
812 : If a child throws, the first child exception is rethrown after
813 : all children complete (exception beats error_code).
814 :
815 : @throws std::invalid_argument From the await, if the range is empty.
816 :
817 : @note If a branch's coroutine is abandoned before it finishes,
818 : `when_all` requests stop on the remaining branches. Teardown
819 : of the branch's execution context is one such case. Once the
820 : last branch has finished or been abandoned, the awaiting
821 : parent is abandoned rather than resumed.
822 :
823 : @par Example
824 : @par !example example_2
825 :
826 :
827 : @param awaitables Range of `results<>`-returning awaitables to
828 : execute concurrently (must not be empty).
829 : The task refers to the range until the await starts. If the
830 : range is a temporary and the task is awaited after the
831 : full-expression that created it, the behavior is undefined.
832 : A forward range whose elements are lvalues is copied, or moved
833 : when passed as an rvalue. The elements of any other range are
834 : moved into a vector. Copying an owning container of move-only
835 : elements, such as `std::vector<task<...>>`, is ill-formed, so
836 : pass it as an rvalue. A view such as `std::span` is copied and
837 : its elements are moved from, so their storage must remain valid
838 : until the await completes.
839 :
840 : @return A task yielding `results<>` whose `ec` is the first child error, if any.
841 :
842 : @see @ref ContextAwaitableRange, @ref when_all
843 : */
844 : template<ContextAwaitableRange R>
845 : requires detail::is_results_v<
846 : awaitable_result_t<std::ranges::range_value_t<R>>>
847 : && std::is_same_v<
848 : detail::results_payload_t<
849 : awaitable_result_t<std::ranges::range_value_t<R>>>,
850 : std::tuple<>>
851 6 : [[nodiscard]] auto when_all(R&& awaitables) -> task<results<>>
852 : {
853 : using OwnedRange = detail::owned_range_t<R>;
854 :
855 : auto count = std::ranges::size(awaitables);
856 : if(count == 0)
857 : throw std::invalid_argument("when_all requires at least one awaitable");
858 :
859 : OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
860 :
861 : detail::when_all_homogeneous_state<std::tuple<>> state(count);
862 :
863 : co_await detail::when_all_homogeneous_launcher<OwnedRange>(
864 : &owned_awaitables, &state);
865 :
866 : if(state.core_.first_exception_)
867 : std::rethrow_exception(state.core_.first_exception_);
868 :
869 : if(state.has_error_.load(std::memory_order_relaxed))
870 : co_return results<>{state.first_error_};
871 :
872 : co_return results<>{};
873 12 : }
874 :
875 : /** Asynchronously execute `results`-returning awaitables concurrently, inspecting error codes.
876 :
877 : Overload selected when all children return results<Ts...>.
878 : The error_code is lifted out of each child into a single outer
879 : results. On success all values are returned; on failure the
880 : first error_code wins.
881 :
882 : @par Await-effects
883 :
884 : Creates and posts one wrapper coroutine per argument to the caller's
885 : executor, in argument order. All children therefore run concurrently,
886 : each awaited with the caller's executor and frame allocator and with
887 : a stop token owned by this operation. The overload requires at least
888 : one awaitable, so there is no empty case.
889 :
890 : A stop request is made on the operation's own stop token when:
891 :
892 : @li a child await-returns a non-zero `ec`, or
893 : @li a child exits via an exception, or
894 : @li the caller's stop token is triggered.
895 :
896 : Every sibling observes that request through the stop token it was
897 : awaited with. The request does not end the operation: the await
898 : completes only after every child has finished.
899 :
900 : @par Await-returns
901 : An object of type `results<P1, ..., Pn>` destructuring as
902 : `[ec, v1, ..., vn]`, where `Pi` is the payload of the i-th child's
903 : `results`. The payload of `results<T>` is `T`. The payload of any
904 : other `results<Ts...>` is `std::tuple<Ts...>`.
905 :
906 : `ec` is the first non-zero `ec` await-returned by a child, in
907 : completion order rather than argument order. The `ec` of every other
908 : child is discarded.
909 :
910 : Each `vi` is the payload the i-th child itself await-returned, even
911 : when that child or a sibling reported an `ec`. A failed child
912 : therefore still contributes whatever payload it produced. This
913 : differs from the range overloads, which discard all payloads once any
914 : child fails.
915 :
916 : If any child exits via an exception, the first such exception is
917 : rethrown instead of await-returning, even when a child also reported
918 : an `ec`.
919 :
920 : @par Await-postcondition
921 : Every child has finished. Each `vi` holds the i-th child's payload,
922 : and `ec` is success only if every child await-returned success.
923 :
924 : @par Remarks
925 : Cancellation follows the stop token of the caller's
926 : @ref await_context.
927 :
928 : @par Thread Safety
929 : The returned task must be awaited from a single execution context.
930 : Child awaitables execute concurrently but complete through the caller's
931 : executor.
932 :
933 : @par Exception Safety
934 : If a child throws, the first child exception is rethrown after
935 : all children complete (exception beats error_code).
936 :
937 : @note If a branch's coroutine is abandoned before it finishes,
938 : `when_all` requests stop on the remaining branches. Teardown
939 : of the branch's execution context is one such case. Once the
940 : last branch has finished or been abandoned, the awaiting
941 : parent is abandoned rather than resumed.
942 :
943 : @par Example
944 : @par !example example_3
945 :
946 : @param awaitables One or more awaitables each returning
947 : results<Ts...>.
948 :
949 : @return A task yielding `results<P1, ..., Pn>`.
950 :
951 : @see @ref ContextAwaitable, @ref when_any
952 : */
953 : template<ContextAwaitable... As>
954 : requires (sizeof...(As) > 0)
955 : && detail::all_results_awaitables<As...>
956 95 : [[nodiscard]] auto when_all(As... awaitables)
957 : -> task<results<
958 : detail::results_payload_t<awaitable_result_t<As>>...>>
959 : {
960 : using result_type = results<
961 : detail::results_payload_t<awaitable_result_t<As>>...>;
962 :
963 : detail::when_all_state<awaitable_result_t<As>...> state;
964 : std::tuple<As...> awaitable_tuple(std::move(awaitables)...);
965 :
966 : co_await detail::when_all_results_launcher<As...>(&awaitable_tuple, &state);
967 :
968 : // Exception always wins over error_code
969 : if(state.core_.first_exception_)
970 : std::rethrow_exception(state.core_.first_exception_);
971 :
972 : auto r = detail::build_when_all_results<result_type>(
973 : detail::extract_results(state));
974 : if(state.has_error_.load(std::memory_order_relaxed))
975 : std::get<0>(r) = state.first_error_;
976 : co_return r;
977 190 : }
978 :
979 : } // namespace capy
980 : } // namespace boost
981 :
982 : #endif
|