-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathstep1.cpp
85 lines (69 loc) · 1.75 KB
/
step1.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
#include <chrono>
#include <coroutine>
#include "debug.hpp"
struct RepeatAwaiter // awaiter(原始指针) / awaitable(operator->)
{
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 RepeatAwaitable // awaitable(operator->)
{
RepeatAwaiter operator co_await() {
return RepeatAwaiter();
}
};
struct Promise {
auto initial_suspend() {
return std::suspend_always();
}
auto final_suspend() noexcept {
return std::suspend_always();
}
void unhandled_exception() {
throw;
}
auto yield_value(int ret) {
mRetValue = ret;
return RepeatAwaiter();
}
void return_void() {
mRetValue = 0;
}
std::coroutine_handle<Promise> get_return_object() {
return std::coroutine_handle<Promise>::from_promise(*this);
}
int mRetValue;
};
struct Task {
using promise_type = Promise;
Task(std::coroutine_handle<promise_type> coroutine)
: mCoroutine(coroutine) {}
std::coroutine_handle<promise_type> mCoroutine;
};
Task hello() {
debug(), "hello 42";
co_yield 42;
debug(), "hello 12";
co_yield 12;
debug(), "hello 6";
co_yield 6;
debug(), "hello 结束";
co_return;
}
int main() {
debug(), "main即将调用hello";
Task t = hello();
debug(), "main调用完了hello";
while (!t.mCoroutine.done()) {
t.mCoroutine.resume();
debug(), "main得到hello结果为",
t.mCoroutine.promise().mRetValue;
}
return 0;
}