-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathstep3.cpp
117 lines (90 loc) · 2.6 KB
/
step3.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
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
#include <chrono>
#include <coroutine>
#include "debug.hpp"
struct RepeatAwaiter
{
bool await_ready() const noexcept { return false; }
std::coroutine_handle<> await_suspend(std::coroutine_handle<> coroutine) const noexcept {
if (coroutine.done())
return std::noop_coroutine();
else
return coroutine;
}
void await_resume() const noexcept {}
};
struct PreviousAwaiter {
std::coroutine_handle<> mPrevious;
bool await_ready() const noexcept { return false; }
std::coroutine_handle<> await_suspend(std::coroutine_handle<> coroutine) const noexcept {
if (mPrevious)
return mPrevious;
else
return std::noop_coroutine();
}
void await_resume() const noexcept {}
};
struct Promise {
auto initial_suspend() {
return std::suspend_always();
}
auto final_suspend() noexcept {
return PreviousAwaiter(mPrevious);
}
void unhandled_exception() {
throw;
}
auto yield_value(int ret) {
mRetValue = ret;
return std::suspend_always();
}
void return_value(int ret) {
mRetValue = ret;
}
std::coroutine_handle<Promise> get_return_object() {
return std::coroutine_handle<Promise>::from_promise(*this);
}
int mRetValue;
std::coroutine_handle<> mPrevious = nullptr;
};
struct Task {
using promise_type = Promise;
Task(std::coroutine_handle<promise_type> coroutine)
: mCoroutine(coroutine) {}
Task(Task &&) = delete;
~Task() {
mCoroutine.destroy();
}
struct Awaiter {
bool await_ready() const { return false; }
std::coroutine_handle<> await_suspend(std::coroutine_handle<> coroutine) const {
mCoroutine.promise().mPrevious = coroutine;
return mCoroutine;
}
auto await_resume() const { return mCoroutine.promise().mRetValue; }
std::coroutine_handle<promise_type> mCoroutine;
};
auto operator co_await() const {
return Awaiter(mCoroutine);
}
std::coroutine_handle<promise_type> mCoroutine;
};
Task world() {
debug(), "world";
co_return 41;
}
Task hello() {
int i = co_await world();
debug(), "hello得到world结果为", i;
co_return i + 1;
}
int main() {
debug(), "main即将调用hello";
Task t = hello();
debug(), "main调用完了hello"; // 其实只创建了task对象,并没有真正开始执行
while (!t.mCoroutine.done()) {
t.mCoroutine.resume();
debug(), "main得到hello结果为",
t.mCoroutine.promise().mRetValue;
}
return 0;
}