-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexecution.bs
10001 lines (7963 loc) · 423 KB
/
execution.bs
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
<pre class='metadata'>
Title: `std::execution`
H1: <code>std::execution</code>
Shortname: D2300
Revision: 11
Status: D
Group: WG21
Date: 2024-06-28
Audience: SG1, LEWG
Editor: Michał Dominiak, griwes@griwes.info
Editor: Georgy Evtushenko, evtushenko.georgy@gmail.com
Editor: Lewis Baker, lewissbaker@gmail.com
Editor: Lucian Radu Teodorescu, lucteo@lucteo.ro
Editor: Lee Howes, xrikcus@gmail.com
Editor: Kirk Shoop, kirk.shoop@gmail.com
Editor: Michael Garland, mgarland@nvidia.com
Editor: Eric Niebler, eric.niebler@gmail.com
Editor: Bryce Adelstein Lelbach, brycelelbach@gmail.com
URL: https://wg21.link/P2300
!Source: <a href="https://github.com/cplusplus/sender-receiver/blob/main/execution.bs">GitHub</a>
Issue Tracking: GitHub https://github.com/cplusplus/sender-receiver/issues
Metadata Order: Editor, This Version, Source, Issue Tracking, Project, Audience
Markup Shorthands: markdown yes
Toggle Diffs: no
No Abstract: yes
Default Biblio Display: inline
Default Highlight: c++
</pre>
<style>
body {
max-width: 60em;
}
pre {
margin-top: 0px;
margin-bottom: 0px;
}
table, th, tr, td {
border: 2px solid black !important;
}
@media (prefers-color-scheme: dark) {
table, th, tr, td {
border: 2px solid white !important;
}
}
.ins, ins, ins *, span.ins, span.ins * {
background-color: #f1fff1;
// color: rgb(0, 136, 0);
text-decoration: underline;
text-decoration-color: rgb(0, 255, 0);
}
.del, del, del *, span.del, span.del * {
background-color: #fff1f1;
// color: rgb(255, 0, 0);
text-decoration: line-through;
text-decoration-color: rgb(255, 0, 0);
}
math, span.math {
font-family: serif;
font-style: italic;
}
ul {
list-style-type: "— ";
}
blockquote {
counter-reset: paragraph;
}
div.numbered, div.newnumbered {
margin-left: 2em;
margin-top: 1em;
margin-bottom: 1em;
}
div.numbered:before, div.newnumbered:before {
position: absolute;
margin-left: -2em;
display-style: block;
}
// div.numbered:before {
// content: counter(paragraph);
// counter-increment: paragraph;
// }
div.newnumbered:before {
content: "�";
}
// div.numbered ul, div.newnumbered ul {
// counter-reset: list_item;
// }
div.numbered li, div.newnumbered li {
margin-left: 3em;
}
div.numbered li:before, div.newnumbered li:before {
position: absolute;
margin-left: -4.8em;
display-style: block;
}
div.numbered li:before {
content: "(" counter(paragraph) "." counter(list_item) ")";
counter-increment: list_item;
}
div.newnumbered li:before {
content: "(�." counter(list_item) ")";
counter-increment: list_item;
}
div.ed-note, span.ed-note {
color: blue !important;
font: initial;
font-family: sans-serif;
}
div.ed-note:before, span.ed-note:before {
content: "[Editorial note: ";
font-style: italic;
}
div.ed-note:after, span.ed-note:after {
content: " — end note]";
font-style: italic;
}
div.ed-note *, span.ed-note * {
color: blue !important;
margin-top: 0em;
margin-bottom: 0em;
}
div.ed-note blockquote {
margin-left: 2em;
}
div.wg21note:before, span.wg21note:before {
content: "[Note: ";
font-style: italic;
}
div.wg21note:after, span.wg21note:after {
content: " — end note]";
font-style: italic;
}
h5 {
font-style: normal; /* turn off italics of h5 headers */
}
div.standardeze {
border-left: 0.1em solid #c0c0c0;
padding-left: 2em;
}
div.block-insert, div.block-insert {
background-color: #f1fff1;
padding-left: 0;
padding-right: 1.6em;
}
div.block-insert pre.highlight {
background-color: transparent;
}
div.hidden,
div.hidden *,
div.hidden span.secno,
div.hidden span.content,
div.hidden a,
div.hidden h1,
div.hidden h2,
div.hidden h3,
div.hidden h4,
div.hidden h5,
div.hidden h6 {
visibility: hidden;
display: none;
white-space: nowrap;
height: 0;
overflow: hidden;
border: 0;
padding: 0;
margin: 0;
margin-block: 0;
line-height: 0;
}
dfn {
font-weight: normal;
}
</style>
# Introduction # {#intro}
This paper proposes a self-contained design for a Standard C++ framework for
managing asynchronous execution on generic execution resources. It is based on
the ideas in [[P0443R14]] and its companion papers.
## Motivation ## {#motivation}
Today, C++ software is increasingly asynchronous and parallel, a trend that is
likely to only continue going forward. Asynchrony and parallelism appears
everywhere, from processor hardware interfaces, to networking, to file I/O, to
GUIs, to accelerators. Every C++ domain and every platform needs to deal with
asynchrony and parallelism, from scientific computing to video games to
financial services, from the smallest mobile devices to your laptop to GPUs in
the world's fastest supercomputer.
While the C++ Standard Library has a rich set of concurrency primitives
(`std::atomic`, `std::mutex`, `std::counting_semaphore`, etc) and lower level
building blocks (`std::thread`, etc), we lack a Standard vocabulary and
framework for asynchrony and parallelism that C++ programmers desperately need.
`std::async`/`std::future`/`std::promise`, C++11's intended exposure for
asynchrony, is inefficient, hard to use correctly, and severely lacking in
genericity, making it unusable in many contexts. We introduced parallel
algorithms to the C++ Standard Library in C++17, and while they are an excellent
start, they are all inherently synchronous and not composable.
This paper proposes a Standard C++ model for asynchrony based around three key
abstractions: schedulers, senders, and receivers, and a set of customizable
asynchronous algorithms.
## Priorities ## {#priorities}
* Be composable and generic, allowing users to write code that can be used with
many different types of execution resources.
* Encapsulate common asynchronous patterns in customizable and reusable
algorithms, so users don't have to invent things themselves.
* Make it easy to be correct by construction.
* Support the diversity of execution resources and execution agents, because not
all execution agents are created equal; some are less capable than others,
but not less important.
* Allow everything to be customized by an execution resource, including transfer
to other execution resources, but don't require that execution resources
customize everything.
* Care about all reasonable use cases, domains and platforms.
* Errors must be propagated, but error handling must not present a burden.
* Support cancellation, which is not an error.
* Have clear and concise answers for where things execute.
* Be able to manage and terminate the lifetimes of objects asynchronously.
## Examples: End User ## {#example-end-user}
In this section we demonstrate the end-user experience of asynchronous
programming directly with the sender algorithms presented in this paper. See
[[#design-sender-factories]], [[#design-sender-adaptors]], and
[[#design-sender-consumers]] for short explanations of the algorithms used in
these code examples.
### Hello world ### {#example-hello-world}
```c++
using namespace std::execution;
scheduler auto sch = thread_pool.scheduler(); // 1
sender auto begin = schedule(sch); // 2
sender auto hi = then(begin, []{ // 3
std::cout << "Hello world! Have an int."; // 3
return 13; // 3
}); // 3
sender auto add_42 = then(hi, [](int arg) { return arg + 42; }); // 4
auto [i] = this_thread::sync_wait(add_42).value(); // 5
```
This example demonstrates the basics of schedulers, senders, and receivers:
1. First we need to get a scheduler from somewhere, such as a thread pool. A
scheduler is a lightweight handle to an execution resource.
2. To start a chain of work on a scheduler, we call
[[#design-sender-factory-schedule]], which returns a sender that completes on
the scheduler. A sender describes asynchronous work and sends a signal
(value, error, or stopped) to some recipient(s) when that work completes.
3. We use sender algorithms to produce senders and compose asynchronous work.
[[#design-sender-adaptor-then]] is a sender adaptor that takes an input
sender and a `std::invocable`, and calls the `std::invocable` on the signal
sent by the input sender. The sender returned by `then` sends the result of
that invocation. In this case, the input sender came from `schedule`, so its
`void`, meaning it won't send us a value, so our `std::invocable` takes no
parameters. But we return an `int`, which will be sent to the next recipient.
4. Now, we add another operation to the chain, again using
[[#design-sender-adaptor-then]]. This time, we get sent a value - the `int`
from the previous step. We add `42` to it, and then return the result.
5. Finally, we're ready to submit the entire asynchronous pipeline and wait for
its completion. Everything up until this point has been completely
asynchronous; the work may not have even started yet. To ensure the work has
started and then block pending its completion, we use
[[#design-sender-consumer-sync_wait]], which will either return a
`std::optional<std::tuple<...>>` with the value sent by the last sender, or
an empty `std::optional` if the last sender sent a stopped signal, or it
throws an exception if the last sender sent an error.
### Asynchronous inclusive scan ### {#example-async-inclusive-scan}
```c++
using namespace std::execution;
sender auto async_inclusive_scan(scheduler auto sch, // 2
std::span<const double> input, // 1
std::span<double> output, // 1
double init, // 1
std::size_t tile_count) // 3
{
std::size_t const tile_size = (input.size() + tile_count - 1) / tile_count;
std::vector<double> partials(tile_count + 1); // 4
partials[0] = init; // 4
return just(std::move(partials)) // 5
| continues_on(sch)
| bulk(tile_count, // 6
[ = ](std::size_t i, std::vector<double>& partials) { // 7
auto start = i * tile_size; // 8
auto end = std::min(input.size(), (i + 1) * tile_size); // 8
partials[i + 1] = *--std::inclusive_scan(begin(input) + start, // 9
begin(input) + end, // 9
begin(output) + start); // 9
}) // 10
| then( // 11
[](std::vector<double>&& partials) {
std::inclusive_scan(begin(partials), end(partials), // 12
begin(partials)); // 12
return std::move(partials); // 13
})
| bulk(tile_count, // 14
[ = ](std::size_t i, std::vector<double>& partials) { // 14
auto start = i * tile_size; // 14
auto end = std::min(input.size(), (i + 1) * tile_size); // 14
std::for_each(begin(output) + start, begin(output) + end, // 14
[&] (double& e) { e = partials[i] + e; } // 14
);
})
| then( // 15
[ = ](std::vector<double>&& partials) { // 15
return output; // 15
}); // 15
}
```
This example builds an asynchronous computation of an inclusive scan:
1. It scans a sequence of `double`s (represented as the `std::span<const
double>` `input`) and stores the result in another sequence of `double`s
(represented as `std::span<double>` `output`).
2. It takes a scheduler, which specifies what execution resource the scan should
be launched on.
3. It also takes a `tile_count` parameter that controls the number of execution
agents that will be spawned.
4. First we need to allocate temporary storage needed for the algorithm, which
we'll do with a `std::vector`, `partials`. We need one `double` of temporary
storage for each execution agent we create.
5. Next we'll create our initial sender with [[#design-sender-factory-just]] and
[[#design-sender-adaptor-continues_on]]. These senders will send the temporary
storage, which we've moved into the sender. The sender has a completion
scheduler of `sch`, which means the next item in the chain will use `sch`.
6. Senders and sender adaptors support composition via `operator|`, similar to
C++ ranges. We'll use `operator|` to attach the next piece of work, which
will spawn `tile_count` execution agents using
[[#design-sender-adaptor-bulk]] (see [[#design-pipeable]] for details).
7. Each agent will call a `std::invocable`, passing it two arguments. The first
is the agent's index (`i`) in the [[#design-sender-adaptor-bulk]] operation,
in this case a unique integer in `[0, tile_count)`. The second argument is
what the input sender sent - the temporary storage.
8. We start by computing the start and end of the range of input and output
elements that this agent is responsible for, based on our agent index.
9. Then we do a sequential `std::inclusive_scan` over our elements. We store the
scan result for our last element, which is the sum of all of our elements,
in our temporary storage `partials`.
10. After all computation in that initial [[#design-sender-adaptor-bulk]] pass
has completed, every one of the spawned execution agents will have written
the sum of its elements into its slot in `partials`.
11. Now we need to scan all of the values in `partials`. We'll do that with a
single execution agent which will execute after the
[[#design-sender-adaptor-bulk]] completes. We create that execution agent
with [[#design-sender-adaptor-then]].
12. [[#design-sender-adaptor-then]] takes an input sender and an
`std::invocable` and calls the `std::invocable` with the value sent by the
input sender. Inside our `std::invocable`, we call `std::inclusive_scan`
on `partials`, which the input senders will send to us.
13. Then we return `partials`, which the next phase will need.
14. Finally we do another [[#design-sender-adaptor-bulk]] of the same shape as
before. In this [[#design-sender-adaptor-bulk]], we will use the scanned
values in `partials` to integrate the sums from other tiles into our
elements, completing the inclusive scan.
15. `async_inclusive_scan` returns a sender that sends the output
`std::span<double>`. A consumer of the algorithm can chain additional work
that uses the scan result. At the point at which `async_inclusive_scan`
returns, the computation may not have completed. In fact, it may not have
even started.
### Asynchronous dynamically-sized read ### {#example-async-dynamically-sized-read}
```c++
using namespace std::execution;
sender_of<std::size_t> auto async_read( // 1
sender_of<std::span<std::byte>> auto buffer, // 1
auto handle); // 1
struct dynamic_buffer { // 3
std::unique_ptr<std::byte[]> data; // 3
std::size_t size; // 3
}; // 3
sender_of<dynamic_buffer> auto async_read_array(auto handle) { // 2
return just(dynamic_buffer{}) // 4
| let_value([handle] (dynamic_buffer& buf) { // 5
return just(std::as_writable_bytes(std::span(&buf.size, 1))) // 6
| async_read(handle) // 7
| then( // 8
[&buf] (std::size_t bytes_read) { // 9
assert(bytes_read == sizeof(buf.size)); // 10
buf.data = std::make_unique<std::byte[]>(buf.size); // 11
return std::span(buf.data.get(), buf.size); // 12
})
| async_read(handle) // 13
| then(
[&buf] (std::size_t bytes_read) {
assert(bytes_read == buf.size); // 14
return std::move(buf); // 15
});
});
}
```
This example demonstrates a common asynchronous I/O pattern - reading a payload
of a dynamic size by first reading the size, then reading the number of bytes
specified by the size:
1. `async_read` is a pipeable sender adaptor. It's a customization point object,
but this is what it's call signature looks like. It takes a sender parameter
which must send an input buffer in the form of a `std::span<std::byte>`, and
a handle to an I/O context. It will asynchronously read into the input
buffer, up to the size of the `std::span`. It returns a sender which will
send the number of bytes read once the read completes.
2. `async_read_array` takes an I/O handle and reads a size from it, and then a
buffer of that many bytes. It returns a sender that sends a `dynamic_buffer`
object that owns the data that was sent.
3. `dynamic_buffer` is an aggregate struct that contains a
`std::unique_ptr<std::byte[]>` and a size.
4. The first thing we do inside of `async_read_array` is create a sender that
will send a new, empty `dynamic_array` object using
[[#design-sender-factory-just]]. We can attach more work to the pipeline
using `operator|` composition (see [[#design-pipeable]] for details).
5. We need the lifetime of this `dynamic_array` object to last for the entire
pipeline. So, we use `let_value`, which takes an input sender and a
`std::invocable` that must return a sender itself (see
[[#design-sender-adaptor-let]] for details). `let_value` sends the value
from the input sender to the `std::invocable`. Critically, the lifetime of
the sent object will last until the sender returned by the `std::invocable`
completes.
6. Inside of the `let_value` `std::invocable`, we have the rest of our logic.
First, we want to initiate an `async_read` of the buffer size. To do that,
we need to send a `std::span` pointing to `buf.size`. We can do that with
[[#design-sender-factory-just]].
7. We chain the `async_read` onto the [[#design-sender-factory-just]] sender
with `operator|`.
8. Next, we pipe a `std::invocable` that will be invoked after the `async_read`
completes using [[#design-sender-adaptor-then]].
9. That `std::invocable` gets sent the number of bytes read.
10. We need to check that the number of bytes read is what we expected.
11. Now that we have read the size of the data, we can allocate storage for it.
12. We return a `std::span<std::byte>` to the storage for the data from the
`std::invocable`. This will be sent to the next recipient in the pipeline.
13. And that recipient will be another `async_read`, which will read the data.
14. Once the data has been read, in another [[#design-sender-adaptor-then]], we
confirm that we read the right number of bytes.
15. Finally, we move out of and return our `dynamic_buffer` object. It will get
sent by the sender returned by `async_read_array`. We can attach more
things to that sender to use the data in the buffer.
## Asynchronous Windows socket `recv` ## {#example-async-windows-socket-recv}
To get a better feel for how this interface might be used by low-level
operations see this example implementation of a cancellable `async_recv()`
operation for a Windows Socket.
```c++
struct operation_base : WSAOVERALAPPED {
using completion_fn = void(operation_base* op, DWORD bytesTransferred, int errorCode) noexcept;
// Assume IOCP event loop will call this when this OVERLAPPED structure is dequeued.
completion_fn* completed;
};
template<class Receiver>
struct recv_op : operation_base {
using operation_state_concept = std::execution::operation_state_t;
recv_op(SOCKET s, void* data, size_t len, Receiver r)
: receiver(std::move(r))
, sock(s) {
this->Internal = 0;
this->InternalHigh = 0;
this->Offset = 0;
this->OffsetHigh = 0;
this->hEvent = NULL;
this->completed = &recv_op::on_complete;
buffer.len = len;
buffer.buf = static_cast<CHAR*>(data);
}
void start() & noexcept {
// Avoid even calling WSARecv() if operation already cancelled
auto st = std::execution::get_stop_token(
std::execution::get_env(receiver));
if (st.stop_requested()) {
std::execution::set_stopped(std::move(receiver));
return;
}
// Store and cache result here in case it changes during execution
const bool stopPossible = st.stop_possible();
if (!stopPossible) {
ready.store(true, std::memory_order_relaxed);
}
// Launch the operation
DWORD bytesTransferred = 0;
DWORD flags = 0;
int result = WSARecv(sock, &buffer, 1, &bytesTransferred, &flags,
static_cast<WSAOVERLAPPED*>(this), NULL);
if (result == SOCKET_ERROR) {
int errorCode = WSAGetLastError();
if (errorCode != WSA_IO_PENDING) {
if (errorCode == WSA_OPERATION_ABORTED) {
std::execution::set_stopped(std::move(receiver));
} else {
std::execution::set_error(std::move(receiver),
std::error_code(errorCode, std::system_category()));
}
return;
}
} else {
// Completed synchronously (assuming FILE_SKIP_COMPLETION_PORT_ON_SUCCESS has been set)
execution::set_value(std::move(receiver), bytesTransferred);
return;
}
// If we get here then operation has launched successfully and will complete asynchronously.
// May be completing concurrently on another thread already.
if (stopPossible) {
// Register the stop callback
stopCallback.emplace(std::move(st), cancel_cb{*this});
// Mark as 'completed'
if (ready.load(std::memory_order_acquire) ||
ready.exchange(true, std::memory_order_acq_rel)) {
// Already completed on another thread
stopCallback.reset();
BOOL ok = WSAGetOverlappedResult(sock, (WSAOVERLAPPED*)this, &bytesTransferred, FALSE, &flags);
if (ok) {
std::execution::set_value(std::move(receiver), bytesTransferred);
} else {
int errorCode = WSAGetLastError();
std::execution::set_error(std::move(receiver),
std::error_code(errorCode, std::system_category()));
}
}
}
}
struct cancel_cb {
recv_op& op;
void operator()() noexcept {
CancelIoEx((HANDLE)op.sock, (OVERLAPPED*)(WSAOVERLAPPED*)&op);
}
};
static void on_complete(operation_base* op, DWORD bytesTransferred, int errorCode) noexcept {
recv_op& self = *static_cast<recv_op*>(op);
if (self.ready.load(std::memory_order_acquire) ||
self.ready.exchange(true, std::memory_order_acq_rel)) {
// Unsubscribe any stop callback so we know that CancelIoEx() is not accessing 'op'
// any more
self.stopCallback.reset();
if (errorCode == 0) {
std::execution::set_value(std::move(self.receiver), bytesTransferred);
} else {
std::execution::set_error(std::move(self.receiver),
std::error_code(errorCode, std::system_category()));
}
}
}
using stop_callback_t = stop_callback_of_t<stop_token_of_t<env_of_t<Receiver>>, cancel_cb>;
Receiver receiver;
SOCKET sock;
WSABUF buffer;
std::optional<stop_callback_t> stopCallback;
std::atomic<bool> ready{false};
};
struct recv_sender {
using sender_concept = std::execution::sender_t;
SOCKET sock;
void* data;
size_t len;
template<class Receiver>
recv_op<Receiver> connect(Receiver r) const {
return recv_op<Receiver>{sock, data, len, std::move(r)};
}
};
recv_sender async_recv(SOCKET s, void* data, size_t len) {
return recv_sender{s, data, len};
}
```
### More end-user examples ### {#example-moar}
#### Sudoku solver #### {#example-sudoku}
This example comes from Kirk Shoop, who ported an example from TBB's
documentation to sender/receiver in his fork of the libunifex repo. It is a
Sudoku solver that uses a configurable number of threads to explore the search
space for solutions.
The sender/receiver-based Sudoku solver can be found
[here](https://github.com/kirkshoop/libunifex/blob/sudoku/examples/sudoku.cpp).
Some things that are worth noting about Kirk's solution:
1. Although it schedules asynchronous work onto a thread pool, and each unit of
work will schedule more work, its use of structured concurrency patterns
make reference counting unnecessary. The solution does not make use of
`shared_ptr`.
2. In addition to eliminating the need for reference counting, the use of
structured concurrency makes it easy to ensure that resources are cleaned up
on all code paths. In contrast, the TBB example that inspired this one
[leaks memory](https://github.com/oneapi-src/oneTBB/issues/568).
For comparison, the TBB-based Sudoku solver can be found
[here](https://github.com/oneapi-src/oneTBB/blob/40a9a1060069d37d5f66912c6ee4cf165144774b/examples/task_group/sudoku/sudoku.cpp).
#### File copy #### {#example-file-copy}
This example also comes from Kirk Shoop which uses sender/receiver to
recursively copy the files a directory tree. It demonstrates how sender/receiver
can be used to do IO, using a scheduler that schedules work on Linux's io_uring.
As with the Sudoku example, this example obviates the need for reference
counting by employing structured concurrency. It uses iteration with an upper
limit to avoid having too many open file handles.
You can find the example
[here](https://github.com/kirkshoop/libunifex/blob/filecopy/examples/file_copy.cpp).
#### Echo server #### {#example-echo-server}
Dietmar Kuehl has proposed networking APIs that use the sender/receiver
abstraction (see \[P2762](https://wg21.link/P2762)). He has implemented an echo
server as a demo. His echo server code can be found
[here](https://github.com/dietmarkuehl/kuhllib/blob/main/src/examples/echo_server.cpp).
Below, I show the part of the echo server code. This code is executed for each
client that connects to the echo server. In a loop, it reads input from a socket
and echos the input back to the same socket. All of this, including the loop, is
implemented with generic async algorithms.
<pre highlight="c++">
outstanding.start(
EX::repeat_effect_until(
EX::let_value(
NN::async_read_some(ptr->d_socket,
context.scheduler(),
NN::buffer(ptr->d_buffer))
| EX::then([ptr](::std::size_t n){
::std::cout << "read='" << ::std::string_view(ptr->d_buffer, n) << "'\n";
ptr->d_done = n == 0;
return n;
}),
[&context, ptr](::std::size_t n){
return NN::async_write_some(ptr->d_socket,
context.scheduler(),
NN::buffer(ptr->d_buffer, n));
})
| EX::then([](auto&&...){})
, [owner = ::std::move(owner)]{ return owner->d_done; }
)
);
</pre>
In this code, `NN::async_read_some` and `NN::async_write_some` are asynchronous
socket-based networking APIs that return senders. `EX::repeat_effect_until`,
`EX::let_value`, and `EX::then` are fully generic sender adaptor algorithms that
accept and return senders.
This is a good example of seamless composition of async IO functions with non-IO
operations. And by composing the senders in this structured way, all the state
for the composite operation -- the `repeat_effect_until` expression and all its
child operations -- is stored altogether in a single object.
## Examples: Algorithms ## {#example-algorithm}
In this section we show a few simple sender/receiver-based algorithm
implementations.
### `then` ### {#example-then}
```c++
namespace stdexec = std::execution;
template <class R, class F>
class _then_receiver : public R {
F f_;
public:
_then_receiver(R r, F f) : R(std::move(r)), f_(std::move(f)) {}
// Customize set_value by invoking the callable and passing the result to
// the inner receiver
template <class... As>
requires std::invocable<F, As...>
void set_value(As&&... as) && noexcept {
try {
stdexec::set_value(std::move(*this).base(), std::invoke((F&&) f_, (As&&) as...));
} catch(...) {
stdexec::set_error(std::move(*this).base(), std::current_exception());
}
}
};
template <stdexec::sender S, class F>
struct _then_sender {
using sender_concept = stdexec::sender_t;
S s_;
F f_;
template <class... Args>
using _set_value_t = stdexec::completion_signatures<
stdexec::set_value_t(std::invoke_result_t<F, Args...>)>;
using _except_ptr_sig =
stdexec::completion_signatures<stdexec::set_error_t(std::exception_ptr)>;
// Compute the completion signatures
template <class Env>
auto get_completion_signatures(Env&& env) && noexcept
-> stdexec::transform_completion_signatures_of<
S, Env, _except_ptr_sig, _set_value_t> {
return {};
}
// Connect:
template <stdexec::receiver R>
auto connect(R r) && -> stdexec::connect_result_t<S, _then_receiver<R, F>> {
return stdexec::connect(
(S&&) s_, _then_receiver{(R&&) r, (F&&) f_});
}
decltype(auto) get_env() const noexcept {
return get_env(s_);
}
};
template <stdexec::sender S, class F>
stdexec::sender auto then(S s, F f) {
return _then_sender<S, F>{(S&&) s, (F&&) f};
}
```
This code builds a `then` algorithm that transforms the value(s) from the input
sender with a transformation function. The result of the transformation becomes
the new value. The other receiver functions (`set_error` and `set_stopped`), as
well as all receiver queries, are passed through unchanged.
In detail, it does the following:
1. Defines a receiver in terms of receiver and an invocable that:
* Defines a constrained `set_value` member function for transforming the
value channel.
* Delegates `set_error` and `set_stopped` to the inner receiver.
2. Defines a sender that aggregates another sender and the invocable, which
defines a `connect` member function that wraps the incoming receiver in the
receiver from (1) and passes it and the incoming sender to
`std::execution::connect`, returning the result. It also defines a
`get_completion_signatures` member function that declares the sender's
completion signatures when executed within a particular environment.
### `retry` ### {#example-retry}
```c++
using namespace std;
namespace stdexec = execution;
template<class From, class To>
concept _decays_to = same_as<decay_t<From>, To>;
// _conv needed so we can emplace construct non-movable types into
// a std::optional.
template<invocable F>
struct _conv {
F f_;
static_assert(is_nothrow_move_constructible_v<F>);
explicit _conv(F f) noexcept : f_((F&&) f) {}
operator invoke_result_t<F>() && {
return ((F&&) f_)();
}
};
template<class S, class R>
struct _retry_op;
// pass through all customizations except set_error, which retries
// the operation.
template<class S, class R>
struct _retry_receiver {
_retry_op<S, R>* o_;
void set_value(auto&&... as) && noexcept {
stdexec::set_value(std::move(o_->r_), (decltype(as)&&) as...);
}
void set_error(auto&&) && noexcept {
o_->_retry(); // This causes the op to be retried
}
void set_stopped() && noexcept {
stdexec::set_stopped(std::move(o_->r_));
}
decltype(auto) get_env() const noexcept {
return get_env(o_->r_);
}
};
// Hold the nested operation state in an optional so we can
// re-construct and re-start it if the operation fails.
template<class S, class R>
struct _retry_op {
using operation_state_concept = stdexec::operation_state_t;
using _child_op_t =
stdexec::connect_result_t<S&, _retry_receiver<S, R>>;
S s_;
R r_;
optional<_child_op_t> o_;
_op(_op&&) = delete;
_op(S s, R r)
: s_(std::move(s)), r_(std::move(r)), o_{_connect()} {}
auto _connect() noexcept {
return _conv{[this] {
return stdexec::connect(s_, _retry_receiver<S, R>{this});
}};
}
void _retry() noexcept {
try {
o_.emplace(_connect()); // potentially-throwing
stdexec::start(*o_);
} catch(...) {
stdexec::set_error(std::move(r_), std::current_exception());
}
}
void start() & noexcept {
stdexec::start(*o_);
}
};
// Helpers for computing the `then` sender's completion signatures:
template <class... Ts>
using _value_t =
stdexec::completion_signatures<stdexec::set_value_t(Ts...)>;
template <class>
using _error_t = stdexec::completion_signatures<>;
using _except_sig =
stdexec::completion_signatures<stdexec::set_error_t(std::exception_ptr)>;
template<class S>
struct _retry_sender {
using sender_concept = stdexec::sender_t;
S s_;
explicit _retry_sender(S s) : s_(std::move(s)) {}
// Declare the signatures with which this sender can complete
template <class Env>
using _compl_sigs =
stdexec::transform_completion_signatures_of<
S&, Env, _except_sig, _value_t, _error_t>;
template <class Env>
auto get_completion_signatures(Env&&) const noexcept -> _compl_sigs<Env> {
return {};
}
template <stdexec::receiver R>
requires stdexec::sender_to<S&, _retry_receiver<S, R>>
_retry_op<S, R> connect(R r) && {
return {std::move(s_), std::move(r)};
}
decltype(auto) get_env() const noexcept {
return get_env(s_);
}
};
template <stdexec::sender S>
stdexec::sender auto retry(S s) {
return _retry_sender{std::move(s)};
}
```
The `retry` algorithm takes a multi-shot sender and causes it to repeat on
error, passing through values and stopped signals. Each time the input sender is
restarted, a new receiver is connected and the resulting operation state is
stored in an `optional`, which allows us to reinitialize it multiple times.
This example does the following:
1. Defines a `_conv` utility that takes advantage of C++17's guaranteed copy
elision to emplace a non-movable type in a `std::optional`.
2. Defines a `_retry_receiver` that holds a pointer back to the operation state.
It passes all customizations through unmodified to the inner receiver owned
by the operation state except for `set_error`, which causes a `_retry()`
function to be called instead.
3. Defines an operation state that aggregates the input sender and receiver, and
declares storage for the nested operation state in an `optional`.
Constructing the operation state constructs a `_retry_receiver` with a
pointer to the (under construction) operation state and uses it to connect
to the input sender.
4. Starting the operation state dispatches to `start` on the inner operation
state.
5. The `_retry()` function reinitializes the inner operation state by connecting
the sender to a new receiver, holding a pointer back to the outer operation
state as before.
6. After reinitializing the inner operation state, `_retry()` calls `start` on
it, causing the failed operation to be rescheduled.
7. Defines a `_retry_sender` that implements a `connect` member function to
return an operation state constructed from the passed-in sender and
receiver.
8. `_retry_sender` also implements a `get_completion_signatures` member function
to describe the ways this sender may complete when executed in a particular
execution resource.
## Examples: Schedulers ## {#example-schedulers}
In this section we look at some schedulers of varying complexity.
### Inline scheduler ### {#example-schedulers-inline}
```c++
namespace stdexec = std::execution;
class inline_scheduler {
template <class R>
struct _op {
using operation_state_concept = operation_state_t;
R rec_;
void start() & noexcept {
stdexec::set_value(std::move(rec_));
}
};
struct _env {
template <class Tag>
inline_scheduler query(stdexec::get_completion_scheduler_t<Tag>) const noexcept {
return {};
}
};
struct _sender {
using sender_concept = stdexec::sender_t;
using _compl_sigs = stdexec::completion_signatures<stdexec::set_value_t()>;
using completion_signatures = _compl_sigs;
template <stdexec::receiver_of<_compl_sigs> R>
_op<R> connect(R rec) noexcept(std::is_nothrow_move_constructible_v<R>) {
return {std::move(rec)};
}
_env get_env() const noexcept {
return {};
}
};
public:
inline_scheduler() = default;
_sender schedule() const noexcept {
return {};
}
bool operator==(const inline_scheduler&) const noexcept = default;
};
```
The inline scheduler is a trivial scheduler that completes immediately and
synchronously on the thread that calls `std::execution::start` on the operation
state produced by its sender. In other words,