-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnested_coroutine.cpp
124 lines (97 loc) · 2.48 KB
/
nested_coroutine.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
118
119
120
121
122
123
124
#include <cassert>
#include <memory>
#include <iostream>
class coroutine {
public:
virtual ~coroutine() {}
virtual bool step() = 0;
};
class nested_coroutine : public coroutine {
public:
void start_nested( std::unique_ptr<nested_coroutine> nested ) {
assert( !nested_ );
nested_ = std::move(nested);
nested_done_ = false;
}
bool step() override {
if( nested_ && !nested_done_ ) {
auto res = nested_->step();
nested_done_ = !res;
return true;
}
return step_impl();
}
template<typename nested_coroutine_type>
std::unique_ptr<nested_coroutine_type> nested_done() {
if( !nested_ || !nested_done_ ) {
return std::unique_ptr<nested_coroutine_type>();
}
auto *rp = dynamic_cast<nested_coroutine_type*>(nested_.get());
assert( rp != nullptr );
nested_.release();
return std::unique_ptr<nested_coroutine_type>(rp);
}
virtual bool step_impl() = 0;
private:
std::unique_ptr<nested_coroutine> nested_;
bool nested_done_;
};
class coroutine2 : public nested_coroutine {
public:
coroutine2() : step_() {}
bool step_impl() override {
std::cout << "coroutine2 step " << step_ << "\n";
if( step_ < 4 ) {
++step_;
return true;
} else {
return false;
}
return true;
}
private:
int step_;
};
class coroutine1 : public nested_coroutine {
public:
coroutine1() : step_(0), is_done_(false) {}
bool step_impl() override {
std::cout << "coroutine1 step " << step_ << "\n";
switch(step_) {
case 0:
step_ = 1;
i_step1_ = 0;
break;
case 1:
{
if( i_step1_ < 5 ) {
auto c2 = nested_done<coroutine2>();
if( c2 ) {
std::cout << "nested done\n";
++i_step1_;
break;
} else {
std::cout << "start nested " << i_step1_ << "\n";
start_nested(std::make_unique<coroutine2>());
break;
}
}
step_ = 2;
break;
}
case 2:
is_done_ = true;
break;
}
return !is_done_;
}
private:
int step_;
bool is_done_;
int i_step1_;
};
int main() {
coroutine1 c1;
while( c1.step() ) {
}
}