source: doc/papers/concurrency/c++-cor/fmt.cpp@ 79b018f3

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 79b018f3 was 8f936bf, checked in by tdelisle <tdelisle@…>, 7 years ago

Got rid of weird yield in fmt example

  • Property mode set to 100644
File size: 1.7 KB
Line 
1
2#include "base.hpp"
3
4struct fmt_cor {
5 struct promise_type {
6 char _value;
7 int g, b;
8
9 fmt_cor get_return_object() {
10 return fmt_cor(std::experimental::coroutine_handle<promise_type>::from_promise(*this));
11 }
12
13 auto initial_suspend() { return suspend_never(); }
14 auto final_suspend() { return suspend_always(); }
15
16 void return_void() {}
17 void unhandled_exception() {}
18 };
19
20 struct get {
21 promise_type * _promise = nullptr;
22
23 bool await_ready() noexcept {
24 return false;
25 }
26
27 void await_suspend(std::experimental::coroutine_handle<promise_type> _coroutine) noexcept {
28 _promise = &_coroutine.promise();
29 }
30 char await_resume() noexcept {
31 assert(_promise);
32 return _promise->_value;
33 }
34 };
35
36 std::experimental::coroutine_handle<promise_type> _coroutine = nullptr;
37
38 explicit fmt_cor(std::experimental::coroutine_handle<promise_type> coroutine)
39 : _coroutine(coroutine)
40 {}
41
42 ~fmt_cor() {
43 if(_coroutine) { _coroutine.destroy(); }
44 }
45
46 fmt_cor() = default;
47 fmt_cor(fmt_cor const &) = delete;
48 fmt_cor& operator=(fmt_cor const &) = delete;
49
50 fmt_cor(fmt_cor&& other) {
51 std::swap(_coroutine, other._coroutine);
52 }
53
54 fmt_cor& operator=(fmt_cor&& other) {
55 if(&other != this) {
56 _coroutine = other._coroutine;
57 other._coroutine = nullptr;
58 }
59 return *this;
60 }
61
62 void send(char a) {
63 _coroutine.promise()._value = a;
64 _coroutine.resume();
65 }
66};
67
68fmt_cor Fmt() {
69 int g; // = co_await fmt_cor::g();
70 int b; // = co_await fmt_cor::b();
71 for(;;) {
72 for(g = 0; g < 5; g++) {
73 for(b = 0; b < 4; b++) {
74 std::cout << co_await fmt_cor::get();
75 }
76 std::cout << " ";
77 }
78 std::cout << std::endl;
79 }
80}
81
82int main() {
83 auto fmt = Fmt();
84 for(int i = 0; i < 41; i++) {
85 fmt.send('a');
86 }
87}
Note: See TracBrowser for help on using the repository browser.