forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03_generators.cpp
68 lines (53 loc) · 1.62 KB
/
03_generators.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 <cassert>
#include <coroutine>
#include <cstdio>
#include <exception>
// ===================================================================
// User defined Generator type and promise_types.
// ===================================================================
template <typename T> class Generator {
public:
struct promise_type;
using co_handle = std::coroutine_handle<promise_type>;
Generator(co_handle handle) : handle_(handle) {}
~Generator() { handle_.destroy(); }
Generator(Generator &) = delete;
Generator(Generator &&) = delete;
T getValue() { return handle_.promise().current_value; }
bool next() {
handle_.resume();
return not handle_.done();
}
private:
co_handle handle_;
};
template <typename T> struct Generator<T>::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(); }
// enable co_yield operator
auto yield_value(const T value) {
current_value = value;
return std::suspend_always();
}
T current_value;
};
// ===================================================================
Generator<int> genInts(int start = 0, int step = 1) noexcept {
auto value = start;
for (int i = 0;; ++i) {
co_yield value;
value += step;
}
}
int main() {
auto gen = genInts();
for (int i = 0; i <= 10; ++i) {
gen.next();
printf("Generating integer: %d\n", gen.getValue());
}
return 0;
}