-
Notifications
You must be signed in to change notification settings - Fork 50
/
channel.cpp
48 lines (40 loc) · 1.06 KB
/
channel.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
#include <co_context/all.hpp>
using namespace co_context;
using namespace std;
// unbuffered channel
channel<std::string> chan;
// buffered channel: more performace
channel<std::string, 8> perf_chan;
task<> produce(std::string tag) {
constexpr int repeat = 2;
for (;;) {
for (int i = 0; i < repeat; ++i) {
co_await chan.release(tag + ": fast produce");
}
for (int i = 0; i < repeat; ++i) {
co_await timeout(1s);
co_await chan.release(tag + ": slow produce");
}
}
}
task<> consume(std::string tag) {
for (;;) {
std::string str{co_await chan.acquire()};
printf("%s: %s\n", tag.c_str(), str.c_str());
co_await timeout(200ms);
}
}
int main() {
io_context ctx[6];
ctx[0].co_spawn(produce("p0"));
ctx[1].co_spawn(produce("p1"));
ctx[2].co_spawn(produce("p2"));
ctx[3].co_spawn(consume("c0"));
ctx[4].co_spawn(consume("c1"));
ctx[5].co_spawn(consume("c2"));
for (auto &c : ctx) {
c.start();
}
ctx[0].join();
return 0;
}