-
Notifications
You must be signed in to change notification settings - Fork 43
/
channel_race_condition.cpp
67 lines (53 loc) · 1.67 KB
/
channel_race_condition.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
/**
* @author github.com/luncliff (luncliff@gmail.com)
*/
#undef NDEBUG
#include <cassert>
#include <mutex>
#include <coroutine/channel.hpp>
#include <coroutine/return.h>
#include <coroutine/windows.h>
#include <latch.h>
using namespace std;
using namespace coro;
using channel_section_t = channel<uint64_t, mutex>;
#if defined(__GNUC__)
using no_return_t = coro::null_frame_t;
#else
using no_return_t = std::nullptr_t;
#endif
int main(int, char*[]) {
static constexpr size_t max_try_count = 6;
uint32_t success{}, failure{};
latch group{2 * max_try_count};
auto send_once = [&](channel_section_t& ch, uint64_t value) -> no_return_t {
co_await continue_on_thread_pool{};
auto w = co_await ch.write(value);
w ? success += 1 : failure += 1;
group.count_down();
};
auto recv_once = [&](channel_section_t& ch) -> no_return_t {
co_await continue_on_thread_pool{};
auto [value, r] = co_await ch.read();
r ? success += 1 : failure += 1;
group.count_down();
};
channel_section_t ch{};
// Spawn coroutines
uint64_t repeat = max_try_count;
while (repeat--) {
recv_once(ch);
send_once(ch, repeat);
}
// Wait for all coroutines...
// !!! user should ensure there is no race for destroying channel !!!
group.wait();
// for same read/write operation,
// channel guarantees all reader/writer will be executed.
assert(failure == 0);
// however, the mutex in the channel is for matching of the coroutines.
// so the counter in the context will be raced
assert(success <= 2 * max_try_count);
assert(success > 0);
return EXIT_SUCCESS;
}