forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_coroutines.cpp
More file actions
60 lines (50 loc) · 1.46 KB
/
02_coroutines.cpp
File metadata and controls
60 lines (50 loc) · 1.46 KB
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
#include <cassert>
#include <coroutine>
#include <cstdio>
#include <exception>
// ===================================================================
// User Defined resumable and promise_types. They are generally the
// same for every case.
// ===================================================================
class resumable {
public:
struct promise_type;
using co_handle = std::coroutine_handle<promise_type>;
resumable(co_handle handle) : handle_(handle) { assert(handle); }
~resumable() { handle_.destroy(); }
resumable(resumable &) = delete;
resumable(resumable &&) = delete;
bool resume() {
if (not handle_.done()) {
handle_.resume();
}
return not handle_.done();
}
private:
co_handle handle_;
};
struct resumable::promise_type {
using co_handle = std::coroutine_handle<promise_type>;
auto get_return_object() { return co_handle::from_promise(*this); }
auto initial_suspend() { return std::suspend_always(); }
auto final_suspend() { return std::suspend_always(); }
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
// ===================================================================
resumable foo() {
printf("<foo> a\n");
co_await std::suspend_always();
printf("<foo> b\n");
co_await std::suspend_always();
printf("<foo> c\n");
}
int main() {
// Coroutine is created in initial suspend state.
resumable r1 = foo();
r1.resume();
r1.resume();
r1.resume();
r1.resume();
return 0;
}