Repository navigation
Expand file tree
/
Copy pathrun_async.hpp
More file actions
1199 lines (966 loc) · 41.5 KB
/
Copy pathrun_async.hpp
File metadata and controls
1199 lines (966 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
// Copyright (c) 2026 Michael Vandeberg
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/cppalliance/capy
//
#ifndef BOOST_CAPY_RUN_ASYNC_HPP
#define BOOST_CAPY_RUN_ASYNC_HPP
#include <boost/capy/detail/config.hpp>
#include <boost/capy/detail/run.hpp>
#include <boost/capy/detail/run_callbacks.hpp>
#include <boost/capy/concept/executor.hpp>
#include <boost/capy/concept/context_runnable.hpp>
#include <boost/capy/ex/abandon.hpp>
#include <boost/capy/ex/execution_context.hpp>
#include <boost/capy/ex/frame_allocator.hpp>
#include <boost/capy/ex/await_context.hpp>
#include <boost/capy/ex/recycling_memory_resource.hpp>
#include <boost/capy/ex/work_guard.hpp>
#include <coroutine>
#include <cstring>
#include <exception>
#include <memory_resource>
#include <new>
#include <stop_token>
#include <type_traits>
namespace boost {
namespace capy {
namespace detail {
/** Match types usable as `run_async` completion handlers.
Excludes the types meaningful to the other `run_async` parameters.
A stop token, memory resource pointer, or allocator argument
therefore selects its dedicated overload by conversion. It does not
deduce as an exact-match handler.
*/
template<class H>
concept RunAsyncHandler =
!std::is_convertible_v<H, std::pmr::memory_resource*> &&
!std::is_convertible_v<H, std::stop_token> &&
!Allocator<H>;
/// Function pointer type for type-erased frame deallocation.
using dealloc_fn = void(*)(void*, std::size_t);
/// Type-erased deallocator implementation for trampoline frames.
template<class Alloc>
void dealloc_impl(void* raw, std::size_t total)
{
static_assert(std::is_same_v<typename Alloc::value_type, frame_unit>);
auto* a = std::launder(reinterpret_cast<Alloc*>(
static_cast<char*>(raw) + total - sizeof(Alloc)));
Alloc ua(std::move(*a));
a->~Alloc();
ua.deallocate(static_cast<frame_unit*>(raw), frame_units(total));
}
/// Awaiter to access the promise from within the coroutine.
template<class Promise>
struct get_promise_awaiter
{
Promise* p_ = nullptr;
bool await_ready() const noexcept { return false; }
bool await_suspend(std::coroutine_handle<Promise> h) noexcept
{
p_ = &h.promise();
return false;
}
Promise& await_resume() const noexcept
{
return *p_;
}
};
/** Internal run_async_trampoline coroutine for run_async.
The run_async_trampoline is allocated BEFORE the task (via C++17 postfix evaluation
order) and serves as the task's continuation. When the task final_suspends,
control returns to the run_async_trampoline which then invokes the appropriate handler.
For value-type allocators, the run_async_trampoline stores a frame_memory_resource
that wraps the allocator. For memory_resource*, it stores the pointer directly.
@tparam Ex The executor type.
@tparam Handlers The handler type (default_handler or handler_pair).
@tparam Alloc The allocator type (value type or memory_resource*).
*/
template<class Ex, class Handlers, class Alloc>
struct run_async_trampoline
{
using invoke_fn = void(*)(void*, Handlers&);
struct promise_type
{
work_guard<Ex> wg_;
Handlers handlers_;
frame_memory_resource<Alloc> resource_;
await_context env_;
invoke_fn invoke_ = nullptr;
void* task_promise_ = nullptr;
// task_h_: raw handle for frame_guard cleanup in make_trampoline.
// task_cont_: continuation wrapping the same handle for executor dispatch.
// Both must reference the same coroutine and be kept in sync.
std::coroutine_handle<> task_h_;
continuation task_cont_;
// Owns the task's segment: abandoning it resumes this
// trampoline, or has it destroyed, to unwind the task.
chain_owner owner_;
~promise_type()
{
// Still owned only when a closed executor destroyed this
// trampoline instead of resuming it to unwind the task.
if(task_h_)
task_h_.destroy();
}
promise_type(Ex& ex, Handlers& h, Alloc& a) noexcept
: wg_(std::move(ex))
, handlers_(std::move(h))
, resource_(std::move(a))
{
}
// Allocates whole frame units: a standard allocator takes no
// alignment argument, and one rebound to std::byte may place
// this frame at byte alignment.
using unit_alloc = typename std::allocator_traits<Alloc>
::template rebind_alloc<frame_unit>;
static_assert(
alignof(unit_alloc) <= frame_alignment,
"Alloc must not be over-aligned");
static constexpr std::size_t
round_up(std::size_t n, std::size_t align) noexcept
{
return (n + align - 1) & ~(align - 1);
}
// The block holds the frame, then the deallocator, then the
// allocator copy, each at its own alignment. The copy comes
// last, where dealloc_impl looks for it.
static constexpr std::size_t
fn_offset(std::size_t size) noexcept
{
return round_up(size, alignof(dealloc_fn));
}
static constexpr std::size_t
block_size(std::size_t size) noexcept
{
return round_up(
fn_offset(size) + sizeof(dealloc_fn),
alignof(unit_alloc)) + sizeof(unit_alloc);
}
static void* operator new(
std::size_t size, Ex const&, Handlers const&, Alloc a)
{
auto const total = block_size(size);
unit_alloc ua(std::move(a));
void* raw = ua.allocate(frame_units(total));
auto* fn_loc = reinterpret_cast<dealloc_fn*>(
static_cast<char*>(raw) + fn_offset(size));
*fn_loc = &dealloc_impl<unit_alloc>;
new (static_cast<char*>(raw) + total - sizeof(unit_alloc))
unit_alloc(std::move(ua));
return raw;
}
static void operator delete(void* ptr, std::size_t size)
{
auto* fn = reinterpret_cast<dealloc_fn*>(
static_cast<char*>(ptr) + fn_offset(size));
(*fn)(ptr, block_size(size));
}
std::pmr::memory_resource* get_resource() noexcept
{
return &resource_;
}
run_async_trampoline get_return_object() noexcept
{
return run_async_trampoline{
std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept
{
return {};
}
std::suspend_never final_suspend() noexcept
{
return {};
}
void return_void() noexcept
{
}
// An exception reaches here only by escaping a handler: a handler
// that threw, or the default handler rethrowing an otherwise
// unhandled task exception. It has no owner to receive it: fail
// fast.
void unhandled_exception() noexcept { std::terminate(); } // LCOV_EXCL_LINE
};
std::coroutine_handle<promise_type> h_;
template<ContextRunnable Task>
static void invoke_impl(void* p, Handlers& h)
{
using R = decltype(std::declval<Task&>().await_resume());
auto& promise = *static_cast<typename Task::promise_type*>(p);
if(promise.exception())
h(promise.exception());
else if constexpr(std::is_void_v<R>)
h();
else
h(std::move(promise.result()));
}
};
/** Specialization for memory_resource* - stores pointer directly.
This avoids double indirection when the user passes a memory_resource*.
*/
template<class Ex, class Handlers>
struct run_async_trampoline<Ex, Handlers, std::pmr::memory_resource*>
{
using invoke_fn = void(*)(void*, Handlers&);
struct promise_type
{
work_guard<Ex> wg_;
Handlers handlers_;
std::pmr::memory_resource* mr_;
await_context env_;
invoke_fn invoke_ = nullptr;
void* task_promise_ = nullptr;
// task_h_: raw handle for frame_guard cleanup in make_trampoline.
// task_cont_: continuation wrapping the same handle for executor dispatch.
// Both must reference the same coroutine and be kept in sync.
std::coroutine_handle<> task_h_;
continuation task_cont_;
// Owns the task's segment: abandoning it resumes this
// trampoline, or has it destroyed, to unwind the task.
chain_owner owner_;
~promise_type()
{
// Still owned only when a closed executor destroyed this
// trampoline instead of resuming it to unwind the task.
if(task_h_)
task_h_.destroy();
}
promise_type(
Ex& ex, Handlers& h, std::pmr::memory_resource* mr) noexcept
: wg_(std::move(ex))
, handlers_(std::move(h))
, mr_(mr)
{
}
static void* operator new(
std::size_t size, Ex const&, Handlers const&,
std::pmr::memory_resource* mr)
{
auto total = size + sizeof(mr);
void* raw = mr->allocate(total, frame_alignment);
std::memcpy(static_cast<char*>(raw) + size, &mr, sizeof(mr));
return raw;
}
static void operator delete(void* ptr, std::size_t size)
{
std::pmr::memory_resource* mr;
std::memcpy(&mr, static_cast<char*>(ptr) + size, sizeof(mr));
auto total = size + sizeof(mr);
mr->deallocate(ptr, total, frame_alignment);
}
std::pmr::memory_resource* get_resource() noexcept
{
return mr_;
}
run_async_trampoline get_return_object() noexcept
{
return run_async_trampoline{
std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept
{
return {};
}
std::suspend_never final_suspend() noexcept
{
return {};
}
void return_void() noexcept
{
}
// See primary template: an escaping handler exception is fatal.
void unhandled_exception() noexcept { std::terminate(); } // LCOV_EXCL_LINE
};
std::coroutine_handle<promise_type> h_;
template<ContextRunnable Task>
static void invoke_impl(void* p, Handlers& h)
{
using R = decltype(std::declval<Task&>().await_resume());
auto& promise = *static_cast<typename Task::promise_type*>(p);
if(promise.exception())
h(promise.exception());
else if constexpr(std::is_void_v<R>)
h();
else
h(std::move(promise.result()));
}
};
/// Coroutine body for run_async_trampoline - invokes handlers then destroys task.
template<class Ex, class Handlers, class Alloc>
run_async_trampoline<Ex, Handlers, Alloc>
make_trampoline(Ex, Handlers, Alloc)
{
// promise_type ctor steals the parameters
auto& p = co_await get_promise_awaiter<
typename run_async_trampoline<Ex, Handlers, Alloc>::promise_type>{};
// Guard ensures the task frame is destroyed even when invoke_
// throws (e.g. default_handler rethrows an unhandled exception).
struct frame_guard
{
std::coroutine_handle<>& h;
~frame_guard() { std::exchange(h, nullptr).destroy(); }
} guard{p.task_h_};
// Resumed with the task unfinished: the segment was abandoned, and
// destroying the task unwinds it without calling a handler.
if(!p.owner_.abandoned())
p.invoke_(p.task_promise_, p.handlers_);
}
} // namespace detail
/** Installs the frame allocator, then starts the task on the executor when called once.
This wrapper holds the run_async_trampoline coroutine, executor, stop token,
and handlers. The run_async_trampoline is allocated when the wrapper is constructed
(before the task due to C++17 postfix evaluation order).
The rvalue ref-qualifier on `operator()` ensures the wrapper can only
be used as a temporary, preventing misuse that would violate LIFO ordering.
@tparam Ex The executor type satisfying the `Executor` concept.
@tparam Handlers The handler type (default_handler or handler_pair).
@tparam Alloc The allocator type (value type or memory_resource*).
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@warning **Always construct the task as the direct argument of the
two-call expression `run_async(ex)(task)`.** The wrapper's constructor
installs the frame allocator in thread-local storage. The task's
`operator new` reads that thread-local state. Splitting the two calls
apart in any of the following ways allocates the task's coroutine
frame under the wrong allocator. Each does so silently, with no
compile error.
@li *Stored wrapper.* Storing the wrapper itself
(`auto w = run_async(ex);`) compiles fine. C++17 guaranteed copy
elision constructs `w` directly from the prvalue. The deleted
copy/move constructors are never considered. What the rvalue
ref-qualifier on `operator()` rejects is calling through that
stored lvalue: `w(my_task())` does not compile, and
`std::move(w)(my_task())` is required instead. The silent
variant is storing the *task*
(`auto t = my_task(); run_async(ex)(std::move(t));`): `t`'s frame
is allocated before `run_async(ex)` ever runs.
@li *Preconstructed task.* Passing an already-constructed task object
has the same effect as the stored-wrapper case. So does passing a
moved-from local, or a task returned from an earlier statement.
The frame exists before the allocator is installed.
@li *Wrapper function.* Forwarding the task through a helper that
itself performs the two-call pattern constructs the task as an
argument to the helper. It is therefore constructed before the
helper's body runs, and so before `run_async` runs. An example is
`submit(ex, my_task())`, where `submit` calls
`run_async(ex)(std::forward<Task>(t))` internally.
See the Frame Allocators guide
(`doc/modules/ROOT/pages/4.coroutines/4g.allocators.adoc`) for the full
C++17-evaluation-order rationale behind this constraint.
@par Example
@par !example example
@see @ref run_async
*/
template<Executor Ex, class Handlers, class Alloc>
class [[nodiscard]] run_async_wrapper
{
detail::run_async_trampoline<Ex, Handlers, Alloc> tr_;
std::stop_token st_;
std::pmr::memory_resource* saved_tls_;
public:
/** Construct the wrapper and install the frame allocator.
Builds the trampoline and saves the current thread-local frame
allocator. Then installs the trampoline's resource as the new
thread-local allocator. The task frame, evaluated as the argument
to @ref operator(), is therefore allocated from that resource.
@param ex The executor on which the task runs.
@param st The stop token for cooperative cancellation.
@param h The completion handlers.
@param a The allocator for frame allocation.
@note When `Alloc` is not `std::pmr::memory_resource*` it must be
nothrow move constructible (enforced by a `static_assert`), which
is what allows this constructor to be `noexcept`. If allocating
the launch state throws, `std::terminate` is called.
*/
run_async_wrapper(
Ex ex,
std::stop_token st,
Handlers h,
Alloc a) noexcept
: tr_(detail::make_trampoline<Ex, Handlers, Alloc>(
std::move(ex), std::move(h), std::move(a)))
, st_(std::move(st))
, saved_tls_(get_current_frame_allocator())
{
if constexpr (!std::is_same_v<Alloc, std::pmr::memory_resource*>)
{
static_assert(
std::is_nothrow_move_constructible_v<Alloc>,
"Allocator must be nothrow move constructible");
}
// Set TLS before task argument is evaluated
set_current_frame_allocator(tr_.h_.promise().get_resource());
}
/** Restore the previously installed frame allocator.
Resets the thread-local frame allocator to the value saved at
construction. A stale pointer to the trampoline's resource
therefore does not outlive the execution context that owns it.
If no task was started, for example because evaluating the task
argument threw, the unused launch state is destroyed, releasing
the executor's work.
*/
~run_async_wrapper()
{
if(tr_.h_)
tr_.h_.destroy();
set_current_frame_allocator(saved_tls_);
}
// Non-copyable, non-movable (must be used immediately)
/** Copy construction is disabled; the wrapper must be used immediately.
@param other The wrapper that would be copied.
*/
run_async_wrapper(run_async_wrapper const& other) = delete;
/** Move construction is disabled; the wrapper must be used immediately.
@param other The wrapper that would be moved from.
*/
run_async_wrapper(run_async_wrapper&& other) = delete;
/** Copy assignment is disabled; the wrapper must be used immediately.
@param other The wrapper that would be assigned from.
@return A reference to `*this`.
*/
run_async_wrapper& operator=(run_async_wrapper const& other) = delete;
/** Move assignment is disabled; the wrapper must be used immediately.
@param other The wrapper that would be moved from.
@return A reference to `*this`.
*/
run_async_wrapper& operator=(run_async_wrapper&& other) = delete;
/** Start the task for execution.
This operator accepts a task and starts it on the executor.
The rvalue ref-qualifier ensures the wrapper is consumed, enforcing
correct LIFO destruction order.
The `await_context` constructed for the task is owned by the trampoline
coroutine and is guaranteed to outlive the task and all awaitables
in its chain. Awaitables may store `await_context const*` without concern
for dangling references.
@throws Any exception thrown by the executor's `dispatch`. The
task is then destroyed without running, and the executor's
work is released.
@tparam Task The ContextRunnable type.
@param t The task to execute. Ownership is transferred to the
run_async_trampoline which destroys it after completion.
*/
template<ContextRunnable Task>
void operator()(Task t) &&
{
auto task_h = t.handle();
auto& task_promise = task_h.promise();
t.release();
auto& p = tr_.h_.promise();
// Inject Task-specific invoke function
p.invoke_ = detail::run_async_trampoline<Ex, Handlers, Alloc>::template invoke_impl<Task>;
p.task_promise_ = &task_promise;
p.task_h_ = task_h;
// Setup task's continuation to return to run_async_trampoline
task_promise.set_continuation(tr_.h_);
p.owner_.bind(tr_.h_, p.wg_.executor());
p.env_ = {p.wg_.executor(), st_, p.get_resource(), &p.owner_};
task_promise.set_environment(&p.env_);
// Start task through executor.
// safe_resume is not needed here: TLS is already saved in the
// constructor (saved_tls_) and restored in the destructor.
p.task_cont_.h = task_h;
p.task_cont_.owner = &p.owner_;
// If dispatch throws, the destructor destroys the trampoline
// and the unstarted task with it.
auto next = p.wg_.executor().dispatch(p.task_cont_);
// From here the trampoline destroys itself when the task ends.
tr_.h_ = nullptr;
next.resume();
}
};
// Executor only (uses default recycling allocator)
/** Bind an executor to produce a launcher. Invoke the launcher with a task to start it.
Use this to start execution of a `task<T>` that was created lazily.
The returned wrapper must be immediately invoked with the task;
storing the wrapper and calling it later violates LIFO ordering.
Uses the default recycling frame allocator for coroutine frames.
With no handlers, the result is discarded. An unhandled exception
thrown by the task calls `std::terminate`. To catch it instead, pass
an error handler that receives it as an `exception_ptr`, or `co_await`
the work inside a coroutine.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread.
@par Example
@par !example example_1
@param ex The executor to execute the task on.
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex>
[[nodiscard]] auto
run_async(Ex ex)
{
auto* mr = ex.context().get_frame_allocator();
return run_async_wrapper<Ex, detail::default_handler, std::pmr::memory_resource*>(
std::move(ex),
std::stop_token{},
detail::default_handler{},
mr);
}
/** Bind an executor and a result handler to produce a launcher. Invoke the launcher with a task to start it.
The handler `h1` is called with the task's result on success. If `h1`
is also invocable with `std::exception_ptr`, it handles exceptions too.
Otherwise, an unhandled exception calls `std::terminate`.
If the task is abandoned before it completes, as a context's teardown
does, no handler is called; the handlers are destroyed with it.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@par Example
@par !example example_2
@param ex The executor to execute the task on.
@param h1 The handler to invoke with the result (and optionally exception).
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex, class H1>
requires detail::RunAsyncHandler<H1>
[[nodiscard]] auto
run_async(Ex ex, H1 h1)
{
auto* mr = ex.context().get_frame_allocator();
return run_async_wrapper<Ex, detail::handler_pair<H1, detail::default_handler>, std::pmr::memory_resource*>(
std::move(ex),
std::stop_token{},
detail::handler_pair<H1, detail::default_handler>{std::move(h1)},
mr);
}
/** Bind an executor and separate result and error handlers to produce a launcher. Invoke the launcher with a task to start it.
The handler `h1` is called with the task's result on success.
The handler `h2` is called with the exception_ptr on failure.
If the task is abandoned before it completes, as a context's teardown
does, no handler is called; the handlers are destroyed with it.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@par Example
@par !example example_3
@param ex The executor to execute the task on.
@param h1 The handler to invoke with the result on success.
@param h2 The handler to invoke with the exception on failure.
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex, class H1, class H2>
requires (detail::RunAsyncHandler<H1> && detail::RunAsyncHandler<H2>)
[[nodiscard]] auto
run_async(Ex ex, H1 h1, H2 h2)
{
auto* mr = ex.context().get_frame_allocator();
return run_async_wrapper<Ex, detail::handler_pair<H1, H2>, std::pmr::memory_resource*>(
std::move(ex),
std::stop_token{},
detail::handler_pair<H1, H2>{std::move(h1), std::move(h2)},
mr);
}
// Ex + stop_token
/** Bind an executor and a stop token to produce a launcher. Invoke the launcher with a task to start it.
The stop token is propagated to the task, enabling cooperative
cancellation. With no handlers, the result is discarded and an
unhandled exception calls `std::terminate`.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread.
@par Example
@par !example example_4
@param ex The executor to execute the task on.
@param st The stop token for cooperative cancellation.
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex>
[[nodiscard]] auto
run_async(Ex ex, std::stop_token st)
{
auto* mr = ex.context().get_frame_allocator();
return run_async_wrapper<Ex, detail::default_handler, std::pmr::memory_resource*>(
std::move(ex),
std::move(st),
detail::default_handler{},
mr);
}
/** Bind an executor, a stop token, and a result handler to produce a launcher. Invoke the launcher with a task to start it.
The stop token is propagated to the task for cooperative cancellation.
The handler `h1` is called with the result on success, and optionally
with exception_ptr if it accepts that type.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@param ex The executor to execute the task on.
@param st The stop token for cooperative cancellation.
@param h1 The handler to invoke with the result (and optionally exception).
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex, class H1>
requires detail::RunAsyncHandler<H1>
[[nodiscard]] auto
run_async(Ex ex, std::stop_token st, H1 h1)
{
auto* mr = ex.context().get_frame_allocator();
return run_async_wrapper<Ex, detail::handler_pair<H1, detail::default_handler>, std::pmr::memory_resource*>(
std::move(ex),
std::move(st),
detail::handler_pair<H1, detail::default_handler>{std::move(h1)},
mr);
}
/** Bind an executor, a stop token, and separate result and error handlers to produce a launcher. Invoke the launcher with a task to start it.
The stop token is propagated to the task for cooperative cancellation.
The handler `h1` is called on success, `h2` on failure.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@param ex The executor to execute the task on.
@param st The stop token for cooperative cancellation.
@param h1 The handler to invoke with the result on success.
@param h2 The handler to invoke with the exception on failure.
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex, class H1, class H2>
requires (detail::RunAsyncHandler<H1> && detail::RunAsyncHandler<H2>)
[[nodiscard]] auto
run_async(Ex ex, std::stop_token st, H1 h1, H2 h2)
{
auto* mr = ex.context().get_frame_allocator();
return run_async_wrapper<Ex, detail::handler_pair<H1, H2>, std::pmr::memory_resource*>(
std::move(ex),
std::move(st),
detail::handler_pair<H1, H2>{std::move(h1), std::move(h2)},
mr);
}
// Ex + memory_resource*
/** Bind an executor and a memory resource to produce a launcher. Invoke the launcher with a task to start it.
The memory resource is used for coroutine frame allocation.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread.
@pre `mr` outlives every task started through the returned wrapper.
@param ex The executor to execute the task on.
@param mr The memory resource for frame allocation.
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex>
[[nodiscard]] auto
run_async(Ex ex, std::pmr::memory_resource* mr)
{
return run_async_wrapper<Ex, detail::default_handler, std::pmr::memory_resource*>(
std::move(ex),
std::stop_token{},
detail::default_handler{},
mr);
}
/** Bind an executor, a memory resource, and a result handler to produce a launcher. Invoke the launcher with a task to start it.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@pre `mr` outlives every task started through the returned wrapper.
@param ex The executor to execute the task on.
@param mr The memory resource for frame allocation.
@param h1 The handler to invoke with the result (and optionally exception).
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex, class H1>
[[nodiscard]] auto
run_async(Ex ex, std::pmr::memory_resource* mr, H1 h1)
{
return run_async_wrapper<Ex, detail::handler_pair<H1, detail::default_handler>, std::pmr::memory_resource*>(
std::move(ex),
std::stop_token{},
detail::handler_pair<H1, detail::default_handler>{std::move(h1)},
mr);
}
/** Bind an executor, a memory resource, and separate result and error handlers to produce a launcher. Invoke the launcher with a task to start it.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@pre `mr` outlives every task started through the returned wrapper.
@param ex The executor to execute the task on.
@param mr The memory resource for frame allocation.
@param h1 The handler to invoke with the result on success.
@param h2 The handler to invoke with the exception on failure.
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex, class H1, class H2>
[[nodiscard]] auto
run_async(Ex ex, std::pmr::memory_resource* mr, H1 h1, H2 h2)
{
return run_async_wrapper<Ex, detail::handler_pair<H1, H2>, std::pmr::memory_resource*>(
std::move(ex),
std::stop_token{},
detail::handler_pair<H1, H2>{std::move(h1), std::move(h2)},
mr);
}
// Ex + stop_token + memory_resource*
/** Bind an executor, a stop token, and a memory resource to produce a launcher. Invoke the launcher with a task to start it.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread.
@pre `mr` outlives every task started through the returned wrapper.
@param ex The executor to execute the task on.
@param st The stop token for cooperative cancellation.
@param mr The memory resource for frame allocation.
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex>
[[nodiscard]] auto
run_async(Ex ex, std::stop_token st, std::pmr::memory_resource* mr)
{
return run_async_wrapper<Ex, detail::default_handler, std::pmr::memory_resource*>(
std::move(ex),
std::move(st),
detail::default_handler{},
mr);
}
/** Bind an executor, a stop token, a memory resource, and a result handler to produce a launcher. Invoke the launcher with a task to start it.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@pre `mr` outlives every task started through the returned wrapper.
@param ex The executor to execute the task on.
@param st The stop token for cooperative cancellation.
@param mr The memory resource for frame allocation.
@param h1 The handler to invoke with the result (and optionally exception).
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex, class H1>
[[nodiscard]] auto
run_async(Ex ex, std::stop_token st, std::pmr::memory_resource* mr, H1 h1)
{
return run_async_wrapper<Ex, detail::handler_pair<H1, detail::default_handler>, std::pmr::memory_resource*>(
std::move(ex),
std::move(st),
detail::handler_pair<H1, detail::default_handler>{std::move(h1)},
mr);
}
/** Bind an executor, a stop token, a memory resource, and separate result and error handlers to produce a launcher. Invoke the launcher with a task to start it.
Construct the task as the direct argument of the two-call expression
`run_async(ex)(task)`.
@par Thread Safety
The wrapper itself should only be used from one thread. The handlers
may be invoked from any thread where the executor schedules work.
@pre `mr` outlives every task started through the returned wrapper.
@param ex The executor to execute the task on.
@param st The stop token for cooperative cancellation.
@param mr The memory resource for frame allocation.
@param h1 The handler to invoke with the result on success.
@param h2 The handler to invoke with the exception on failure.
@return A wrapper that accepts a `task<T>` for immediate execution.
@see @ref task
@see @ref Executor
@see @ref run_async_wrapper
*/
template<Executor Ex, class H1, class H2>
[[nodiscard]] auto
run_async(Ex ex, std::stop_token st, std::pmr::memory_resource* mr, H1 h1, H2 h2)
{