-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1 resume.cpp
68 lines (63 loc) · 1.84 KB
/
1 resume.cpp
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
#include<iostream>
#include<string>
#include<experimental/generator>
#include<experimental/coroutine>
namespace stdx = std::experimental;
using stdx::coroutine_handle;
using std::cout;
struct ResumableThing {
struct promise_type {
// factory function
ResumableThing get_return_object() {
return ResumableThing(coroutine_handle<promise_type>::from_promise(*this));
}
auto initial_suspend() { return stdx::suspend_never(); }
auto final_suspend() { return stdx::suspend_never(); }
void return_void() {}
};
coroutine_handle<promise_type> _coroutine = nullptr;
explicit ResumableThing(coroutine_handle<promise_type> coroutine)
: _coroutine(coroutine) {
}
~ResumableThing() {
if (_coroutine) _coroutine.destroy();
}
ResumableThing() = default;
ResumableThing(ResumableThing const&) = delete; // no copy
ResumableThing& operator=(ResumableThing const&) = delete; // no copy assign
ResumableThing(ResumableThing&& other) // move constructor
: _coroutine(other._coroutine) {
other._coroutine = nullptr;
}
ResumableThing& operator=(ResumableThing&& other) { // move assign
if (&other != this) {
_coroutine = other._coroutine;
other._coroutine = nullptr;
}
}
auto resume() { _coroutine.resume(); }
};
ResumableThing countCoroutine() {
cout << "count called\n";
for (int i = 0; ; ++i) {
co_await stdx::suspend_always();
cout << "count resumed\n";
}
}
ResumableThing namedCounter(std::string name) {
cout << "counter(" << name << ") was called\n";
for (int i = 1; ; ++i) {
co_await stdx::suspend_always();
cout << "counter(" << name << ") resumed #" << i << "\n";
}
}
int main() {
ResumableThing c = countCoroutine();
c.resume();
ResumableThing a = namedCounter("a");
ResumableThing b = namedCounter("b");
a.resume();
b.resume();
b.resume();
a.resume();
};