-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathex016-wait_group.cpp
78 lines (58 loc) · 1.85 KB
/
ex016-wait_group.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
69
70
71
72
73
74
75
76
77
78
#include <chrono>
#include <iostream>
#include <string>
#include <syncstream>
#include "coke/sleep.h"
#include "coke/wait_group.h"
#include "coke/wait.h"
/**
* This example shows the basic usage of coke::WaitGroup.
*/
std::string current();
coke::Task<> subworker(coke::WaitGroup &wg, int i) {
std::osyncstream os(std::cout);
auto ms = std::chrono::milliseconds(i * 100);
co_await coke::sleep(ms);
os << current() << "SubWorker " << i << " done" << std::endl;
os.emit();
wg.done();
}
coke::Task<> worker(coke::WaitGroup &wg, int i) {
std::osyncstream os(std::cout);
auto ms = std::chrono::milliseconds(i * 100);
std::emit_on_flush(os);
co_await coke::sleep(ms);
if (i % 2 == 0) {
// The worker can add count to wg and then detach subworkers,
// but just before wg.done is called.
wg.add(1);
os << current() << "Detach subworker " << i << std::endl;
coke::detach(subworker(wg, i));
}
os << current() << "Worker " << i << " done" << std::endl;
wg.done();
// WaitGroup::done usually should be called before the coroutine ends.
// After done is called, wg maybe destroyed, DO NOT use it any more.
}
coke::Task<> async_main(int nworkers) {
std::osyncstream os(std::cout);
coke::WaitGroup wg;
std::emit_on_flush(os);
for (int i = 0; i < nworkers; i++) {
wg.add(1);
os << current() << "Detach worker " << i << std::endl;
coke::detach(worker(wg, i));
}
co_await wg.wait();
os << current() << "Wait done" << std::endl;
}
int main() {
coke::sync_wait(async_main(6));
return 0;
}
std::string current() {
static auto start = std::chrono::steady_clock::now();
auto now = std::chrono::steady_clock::now();
std::chrono::duration<double> d = now - start;
return "[" + std::to_string(d.count()) + "s] ";
}