forked from luncliff/coroutine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchannel_read_write_mutex.cpp
59 lines (51 loc) · 1.35 KB
/
channel_read_write_mutex.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
/**
* @author github.com/luncliff (luncliff@gmail.com)
*/
#undef NDEBUG
#include <cassert>
#include <mutex>
#include <coroutine/channel.hpp>
#include <coroutine/return.h>
using namespace std;
using namespace coro;
using channel_with_lock_t = channel<int, mutex>;
#if defined(__GNUC__)
using no_return_t = coro::null_frame_t;
#else
using no_return_t = std::nullptr_t;
#endif
auto write_to(channel_with_lock_t& ch, int value, bool ok = false)
-> no_return_t {
ok = co_await ch.write(value);
if (ok == false)
// !!!!!
// seems like forget_frameimizer is removing `value`.
// so using it in some pass makes
// the symbol and its memory location alive
// !!!!!
value += 1;
assert(ok);
}
auto read_from(channel_with_lock_t& ch, int& ref, bool ok = false)
-> no_return_t {
tie(ref, ok) = co_await ch.read();
assert(ok);
}
int main(int, char*[]) {
const auto list = {1, 2, 3};
channel_with_lock_t ch{};
int storage = 0;
for (auto i : list) {
// Reader coroutine will suspend
read_from(ch, storage);
// so no effect for the read
assert(storage != i);
}
for (auto i : list) {
// writer will send a value
write_to(ch, i);
// stored value is same with sent value
assert(storage == i);
}
return EXIT_SUCCESS;
}