forked from luncliff/coroutine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel_ownership_consumer.cpp
57 lines (48 loc) · 1.36 KB
/
channel_ownership_consumer.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
/**
* @author github.com/luncliff (luncliff@gmail.com)
*/
#undef NDEBUG
#include <cassert>
#include <coroutine/channel.hpp>
#include <coroutine/return.h>
using namespace std;
using namespace coro;
#if defined(__GNUC__)
using no_return_t = coro::null_frame_t;
#else
using no_return_t = std::nullptr_t;
#endif
constexpr int bye = 0;
auto producer(channel<int>& ch) -> no_return_t {
for (int msg : {1, 2, 3, bye}) {
auto ok = co_await ch.write(msg);
// ok == true: we sent a value
assert(ok);
}
puts("producer loop exit");
// we know that we sent the `bye`,
// but will send again to check `ok` becomes `false`
int msg = -1;
auto ok = co_await ch.write(msg);
// ok == false: channel is going to be destroyed (no effect for read/write)
assert(ok == false);
puts("channel destruction detected");
}
auto consumer_owner() -> no_return_t {
channel<int> ch{};
producer(ch); // start a producer routine
// the type doesn't support for-co_await for now
for (auto [msg, ok] = co_await ch.read(); ok;
tie(msg, ok) = co_await ch.read()) {
// ok == true: we sent a value
if (msg == bye) {
puts("consumer loop exit");
break;
}
}
puts("consumer_owner is going to return");
}
int main(int, char*[]) {
consumer_owner();
return EXIT_SUCCESS;
}