-
Notifications
You must be signed in to change notification settings - Fork 6
/
execution.bs
7810 lines (6048 loc) · 387 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: 8
Status: D
Group: WG21
Audience: SG1, LEWG
Editor: Michał Dominiak, [email protected]
Editor: Georgy Evtushenko, [email protected]
Editor: Lewis Baker, [email protected]
Editor: Lucian Radu Teodorescu, [email protected]
Editor: Lee Howes, [email protected]
Editor: Kirk Shoop, [email protected]
Editor: Michael Garland, [email protected]
Editor: Eric Niebler, [email protected]
Editor: Bryce Adelstein Lelbach, [email protected]
URL: https://wg21.link/P2300
!Source: <a href="https://github.com/brycelelbach/wg21_p2300_execution/blob/main/execution.bs">GitHub</a>
Issue Tracking: GitHub https://github.com/brycelelbach/wg21_p2300_execution/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>
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: rgb(200, 250, 200);
color: rgb(0, 136, 0);
text-decoration: none;
}
.del, del, del *, span.del, span.del * {
background-color: rgb(250, 200, 200);
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 {
color: blue !important;
margin-left: 2em;
}
div.ed-note:before {
content: "[Editorial note: ";
font-style: italic;
}
div.ed-note:after {
content: " -- end note]";
font-style: italic;
}
div.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 */
}
</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
| transfer(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-transfer]]. 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_writeable_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<typename Receiver>
struct recv_op : operation_base {
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);
}
friend void tag_invoke(std::execution::start_t, recv_op& self) noexcept {
// Avoid even calling WSARecv() if operation already cancelled
auto st = std::execution::get_stop_token(
std::get_env(self.receiver));
if (st.stop_requested()) {
std::execution::set_stopped(std::move(self.receiver));
return;
}
// Store and cache result here in case it changes during execution
const bool stopPossible = st.stop_possible();
if (!stopPossible) {
self.ready.store(true, std::memory_order_relaxed);
}
// Launch the operation
DWORD bytesTransferred = 0;
DWORD flags = 0;
int result = WSARecv(self.sock, &self.buffer, 1, &bytesTransferred, &flags,
static_cast<WSAOVERLAPPED*>(&self), NULL);
if (result == SOCKET_ERROR) {
int errorCode = WSAGetLastError();
if (errorCode != WSA_IO_PENDING)) {
if (errorCode == WSA_OPERATION_ABORTED) {
std::execution::set_stopped(std::move(self.receiver));
} else {
std::execution::set_error(std::move(self.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(self.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
self.stopCallback.emplace(std::move(st), cancel_cb{self});
// Mark as 'completed'
if (self.ready.load(std::memory_order_acquire) ||
self.ready.exchange(true, std::memory_order_acq_rel)) {
// Already completed on another thread
self.stopCallback.reset();
BOOL ok = WSAGetOverlappedResult(self.sock, (WSAOVERLAPPED*)&self, &bytesTransferred, FALSE, &flags);
if (ok) {
std::execution::set_value(std::move(self.receiver), bytesTransferred);
} else {
int errorCode = WSAGetLastError();
std::execution::set_error(std::move(self.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 (ready.load(std::memory_order_acquire) ||
ready.exchange(true, std::memory_order_acq_rel)) {
// Unsubscribe any stop-callback so we know that CancelIoEx() is not accessing 'op'
// any more
stopCallback.reset();
if (errorCode == 0) {
std::execution::set_value(std::move(receiver), bytesTransferred);
} else {
std::execution::set_error(std::move(receiver),
std::error_code(errorCode, std::system_category()));
}
}
}
Receiver receiver;
SOCKET sock;
WSABUF buffer;
std::optional<typename stop_callback_type_t<Receiver>
::template callback_type<cancel_cb>> stopCallback;
std::atomic<bool> ready{false};
};
struct recv_sender {
using is_sender = void;
SOCKET sock;
void* data;
size_t len;
template<typename Receiver>
friend recv_op<Receiver> tag_invoke(std::execution::connect_t,
const recv_sender& s,
Receiver r) {
return recv_op<Receiver>{s.sock, s.data, s.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 asychronous 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 a hobby project that implements networking APIs on top of sender/receiver. He recently 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 exec = std::execution;
template<class R, class F>
class _then_receiver
: exec::receiver_adaptor<_then_receiver<R, F>, R> {
friend exec::receiver_adaptor<_then_receiver, R>;
F f_;
// Customize set_value by invoking the callable and passing the result to the inner receiver
template<class... As>
void set_value(As&&... as) && noexcept try {
exec::set_value(std::move(*this).base(), std::invoke((F&&) f_, (As&&) as...));
} catch(...) {
exec::set_error(std::move(*this).base(), std::current_exception());
}
public:
_then_receiver(R r, F f)
: exec::receiver_adaptor<_then_receiver, R>{std::move(r)}
, f_(std::move(f)) {}
};
template<exec::sender S, class F>
struct _then_sender {
using is_sender = void;
S s_;
F f_;
template <class... Args>
using _set_value_t = exec::completion_signatures<
exec::set_value_t(std::invoke_result_t<F, Args...>)>;
// Compute the completion signatures
template<class Env>
friend auto tag_invoke(exec::get_completion_signatures_t, _then_sender&&, Env)
-> exec::transform_completion_signatures_of<S, Env,
exec::completion_signatures<exec::set_error_t(std::exception_ptr)>,
_set_value_t>;
// Connect:
template<exec::receiver R>
friend auto tag_invoke(exec::connect_t, _then_sender&& self, R r)
-> exec::connect_result_t<S, _then_receiver<R, F>> {
return exec::connect(
(S&&) self.s_, _then_receiver<R, F>{(R&&) r, (F&&) self.f_});
}
friend decltype(auto) tag_invoke(get_env_t, const _then_sender& self) noexcept {
return get_env(self.s_);
}
};
template<exec::sender S, class F>
exec::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 `execution::receiver_adaptor` that aggregates
another receiver and an invocable that:
* Defines a constrained `tag_invoke` overload for transforming the value
channel.
* Defines another constrained overload of `tag_invoke` that passes all other
customizations through unchanged.
The `tag_invoke` overloads are actually implemented by
`execution::receiver_adaptor`; they dispatch either to named members, as
shown above with `_then_receiver::set_value`, or to the adapted receiver.
2. Defines a sender that aggregates another sender and the invocable, which defines a `tag_invoke` customization for `std::execution::connect` 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 `tag_invoke` customization of `get_completion_signatures` that declares the sender's completion signatures when executed within a particular environment.
### `retry` ### {#example-retry}
```c++
using namespace std;
namespace exec = 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>
requires is_nothrow_move_constructible_v<F>
struct _conv {
F f_;
explicit _conv(F f) noexcept : f_((F&&) f) {}
operator invoke_result_t<F>() && {
return ((F&&) f_)();
}
};
template<class S, class R>
struct _op;
// pass through all customizations except set_error, which retries the operation.
template<class S, class R>
struct _retry_receiver
: exec::receiver_adaptor<_retry_receiver<S, R>> {
_op<S, R>* o_;
R&& base() && noexcept { return (R&&) o_->r_; }
const R& base() const & noexcept { return o_->r_; }
explicit _retry_receiver(_op<S, R>* o) : o_(o) {}
void set_error(auto&&) && noexcept {
o_->_retry(); // This causes the op to be retried
}
};
// 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 _op {
S s_;
R r_;
optional<
exec::connect_result_t<S&, _retry_receiver<S, R>>> o_;
_op(S s, R r): s_((S&&)s), r_((R&&)r), o_{_connect()} {}
_op(_op&&) = delete;
auto _connect() noexcept {
return _conv{[this] {
return exec::connect(s_, _retry_receiver<S, R>{this});
}};
}
void _retry() noexcept try {
o_.emplace(_connect()); // potentially-throwing
exec::start(*o_);
} catch(...) {
exec::set_error((R&&) r_, std::current_exception());
}
friend void tag_invoke(exec::start_t, _op& o) noexcept {
exec::start(*o.o_);
}
};
template<class S>
struct _retry_sender {
using is_sender = void;
S s_;
explicit _retry_sender(S s) : s_((S&&) s) {}
template <class... Ts>
using _value_t =
exec::completion_signatures<exec::set_value_t(Ts...)>;
template <class>
using _error_t = exec::completion_signatures<>;
// Declare the signatures with which this sender can complete
template <class Env>
friend auto tag_invoke(exec::get_completion_signatures_t, const _retry_sender&, Env)
-> exec::transform_completion_signatures_of<S&, Env,
exec::completion_signatures<exec::set_error_t(std::exception_ptr)>,
_value_t, _error_t>;
template<exec::receiver R>
friend _op<S, R> tag_invoke(exec::connect_t, _retry_sender&& self, R r) {
return {(S&&) self.s_, (R&&) r};
}
friend decltype(auto) tag_invoke(exec::get_env_t, const _retry_sender& self) noexcept {
return get_env(self.s_);
}
};
template<exec::sender S>
exec::sender auto retry(S s) {
return _retry_sender{(S&&) 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 aggregated 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 the `connect` customization point to return
an operation state constructed from the passed-in sender and receiver.
8. `_retry_sender` also implements the `get_completion_signatures` customization point 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++
class inline_scheduler {
template <class R>
struct _op {
[[no_unique_address]] R rec_;
friend void tag_invoke(std::execution::start_t, _op& op) noexcept {
std::execution::set_value((R&&) op.rec_);
}
};
struct _env {
template <class Tag>
friend inline_scheduler tag_invoke(
std::execution::get_completion_scheduler_t<Tag>, _env) noexcept {
return {};
}
};
struct _sender {
using is_sender = void;
using completion_signatures =
std::execution::completion_signatures<std::execution::set_value_t()>;
template <class R>
friend auto tag_invoke(std::execution::connect_t, _sender, R&& rec)
noexcept(std::is_nothrow_constructible_v<std::remove_cvref_t<R>, R>)
-> _op<std::remove_cvref_t<R>> {
return {(R&&) rec};
}
friend _env tag_invoke(exec::get_env_t, _sender) noexcept {
return {};
}
};
friend _sender tag_invoke(std::execution::schedule_t, const inline_scheduler&) noexcept {
return {};
}
public:
inline_scheduler() = default;
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, <code>start(connect(schedule(<i>inline-scheduler</i>), receiver))</code> is
just a fancy way of saying `set_value(receiver)`, with the exception of the fact that `start`
wants to be passed an lvalue.
Although not a particularly useful scheduler, it serves to illustrate the basics of
implementing one. The `inline_scheduler`:
1. Customizes `execution::schedule` to return an instance of the sender type
`_sender`.
2. The `_sender` type models the `sender` concept and provides the metadata
needed to describe it as a sender of no values
and that never calls `set_error` or `set_stopped`. This
metadata is provided with the help of the `execution::completion_signatures`
utility.
3. The `_sender` type customizes `execution::connect` to accept a receiver of no
values. It returns an instance of type `_op` that holds the receiver by
value.
4. The operation state customizes `std::execution::start` to call
`std::execution::set_value` on the receiver.
### Single thread scheduler ### {#example-single-thread}
This example shows how to create a scheduler for an execution resource that consists of a single
thread. It is implemented in terms of a lower-level execution resource called `std::execution::run_loop`.
```c++
class single_thread_context {
std::execution::run_loop loop_;
std::thread thread_;
public:
single_thread_context()
: loop_()
, thread_([this] { loop_.run(); })
{}
~single_thread_context() {
loop_.finish();
thread_.join();
}
auto get_scheduler() noexcept {
return loop_.get_scheduler();
}
std::thread::id get_thread_id() const noexcept {
return thread_.get_id();
}
};
```
The `single_thread_context` owns an event loop and a thread to drive it. In the destructor, it tells the event
loop to finish up what it's doing and then joins the thread, blocking for the event loop to drain.
The interesting bits are in the `execution::run_loop` context implementation. It
is slightly too long to include here, so we only provide [a reference to
it](https://github.com/NVIDIA/stdexec/blob/c2cdb2a2abe2b29a34cf277728319d6ca92ec0bb/include/stdexec/execution.hpp#L3916-L4101),
but there is one noteworthy detail about its implementation: It uses space in
its operation states to build an intrusive linked list of work items. In
structured concurrency patterns, the operation states of nested operations
compose statically, and in an algorithm like `this_thread::sync_wait`, the
composite operation state lives on the stack for the duration of the operation.
The end result is that work can be scheduled onto this thread with zero
allocations.
## Examples: Server theme ## {#example-server}
In this section we look at some examples of how one would use senders to implement an HTTP server. The examples ignore the low-level details of the HTTP server and looks at how senders can be combined to achieve the goals of the project.
General application context:
* server application that processes images
* execution resources:
- 1 dedicated thread for network I/O
- N worker threads used for CPU-intensive work
- M threads for auxiliary I/O
- optional GPU context that may be used on some types of servers
* all parts of the applications can be asynchronous
* no locks shall be used in user code
### Composability with `execution::let_*` ### {#example-server-let}
Example context:
- we are looking at the flow of processing an HTTP request and sending back the response
- show how one can break the (slightly complex) flow into steps with `execution::let_*` functions
- different phases of processing HTTP requests are broken down into separate concerns
- each part of the processing might use different execution resources (details not shown in this example)
- error handling is generic, regardless which component fails; we always send the right response to the clients
Goals:
- show how one can break more complex flows into steps with let_* functions
- exemplify the use of `let_value`, `let_error`, `let_stopped`, and `just` algorithms
```c++
namespace ex = std::execution;
// Returns a sender that yields an http_request object for an incoming request
ex::sender auto schedule_request_start(read_requests_ctx ctx) {...}
// Sends a response back to the client; yields a void signal on success
ex::sender auto send_response(const http_response& resp) {...}
// Validate that the HTTP request is well-formed; forwards the request on success
ex::sender auto validate_request(const http_request& req) {...}
// Handle the request; main application logic
ex::sender auto handle_request(const http_request& req) {
//...
return ex::just(http_response{200, result_body});
}
// Transforms server errors into responses to be sent to the client
ex::sender auto error_to_response(std::exception_ptr err) {
try {
std::rethrow_exception(err);
} catch (const std::invalid_argument& e) {
return ex::just(http_response{404, e.what()});
} catch (const std::exception& e) {
return ex::just(http_response{500, e.what()});
} catch (...) {
return ex::just(http_response{500, "Unknown server error"});
}
}
// Transforms cancellation of the server into responses to be sent to the client
ex::sender auto stopped_to_response() {
return ex::just(http_response{503, "Service temporarily unavailable"});
}
//...
// The whole flow for transforming incoming requests into responses
ex::sender auto snd =
// get a sender when a new request comes
schedule_request_start(the_read_requests_ctx)
// make sure the request is valid; throw if not
| ex::let_value(validate_request)
// process the request in a function that may be using a different execution resource
| ex::let_value(handle_request)
// If there are errors transform them into proper responses
| ex::let_error(error_to_response)
// If the flow is cancelled, send back a proper response
| ex::let_stopped(stopped_to_response)
// write the result back to the client
| ex::let_value(send_response)
// done
;
// execute the whole flow asynchronously
ex::start_detached(std::move(snd));
```
The example shows how one can separate out the concerns for interpreting requests, validating requests, running the main logic for handling the request, generating error responses, handling cancellation and sending the response back to the client.
They are all different phases in the application, and can be joined together with the `let_*` functions.
All our functions return `execution::sender` objects, so that they can all generate success, failure and cancellation paths.
For example, regardless where an error is generated (reading request, validating request or handling the response), we would have one common block to handle the error, and following error flows is easy.
Also, because of using `execution::sender` objects at any step, we might expect any of these steps to be completely asynchronous; the overall flow doesn't care.
Regardless of the execution resource in which the steps, or part of the steps are executed in, the flow is still the same.
### Moving between execution resources with `execution::on` and `execution::transfer` ### {#example-server-on}
Example context:
- reading data from the socket before processing the request
- reading of the data is done on the I/O context
- no processing of the data needs to be done on the I/O context
Goals:
- show how one can change the execution resource
- exemplify the use of `on` and `transfer` algorithms
```c++
namespace ex = std::execution;
size_t legacy_read_from_socket(int sock, char* buffer, size_t buffer_len) {}
void process_read_data(const char* read_data, size_t read_len) {}
//...
// A sender that just calls the legacy read function
auto snd_read = ex::just(sock, buf, buf_len) | ex::then(legacy_read_from_socket);
// The entire flow
auto snd =
// start by reading data on the I/O thread
ex::on(io_sched, std::move(snd_read))
// do the processing on the worker threads pool
| ex::transfer(work_sched)
// process the incoming data (on worker threads)
| ex::then([buf](int read_len) { process_read_data(buf, read_len); })
// done
;
// execute the whole flow asynchronously
ex::start_detached(std::move(snd));
```
The example assume that we need to wrap some legacy code of reading sockets, and handle execution resource switching.
(This style of reading from socket may not be the most efficient one, but it's working for our purposes.)
For performance reasons, the reading from the socket needs to be done on the I/O thread, and all the processing needs to happen on a work-specific execution resource (i.e., thread pool).
Calling `execution::on` will ensure that the given sender will be started on the given scheduler.
In our example, `snd_read` is going to be started on the I/O scheduler.
This sender will just call the legacy code.
The completion-signal will be issued in the I/O execution resource, so we have to move it to the work thread pool.
This is achieved with the help of the `execution::transfer` algorithm.
The rest of the processing (in our case, the last call to `then`) will happen in the work thread pool.
The reader should notice the difference between `execution::on` and `execution::transfer`.
The `execution::on` algorithm will ensure that the given sender will start in the specified context, and doesn't care where the completion-signal for that sender is sent.
The `execution::transfer` algorithm will not care where the given sender is going to be started, but will ensure that the completion-signal of will be transferred to the given context.
## What this proposal is **not** ## {#intro-is-not}
This paper is not a patch on top of [[P0443R14]]; we are not asking to update the existing paper, we are asking to retire it in favor of this paper, which is already self-contained; any example code within this paper can be written in Standard C++, without the need
to standardize any further facilities.
This paper is not an alternative design to [[P0443R14]]; rather, we have taken the design in the current executors paper, and applied targeted fixes to allow it to fulfill the promises of the sender/receiver model, as well as provide all the facilities we consider
essential when writing user code using standard execution concepts; we have also applied the guidance of removing one-way executors from the paper entirely, and instead provided an algorithm based around senders that serves the same purpose.
## Design changes from P0443 ## {#intro-compare}
1. The `executor` concept has been removed and all of its proposed functionality
is now based on schedulers and senders, as per SG1 direction.
2. Properties are not included in this paper. We see them as a possible future
extension, if the committee gets more comfortable with them.
3. Senders now advertise what scheduler, if any, their evaluation will complete
on.
4. The places of execution of user code in P0443 weren't precisely defined,
whereas they are in this paper. See [[#design-propagation]].
5. P0443 did not propose a suite of sender algorithms necessary for writing