blob: 567e3db25d326a4dc6b1e9767660940619b04f1d (
plain) (
blame)
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
|
#include <latch.h>
#include <chrono>
#include <thread>
#include <vector>
#include <cassert>
#include <cstdio>
constexpr unsigned kNumThreads = 16;
int main() {
latch gate(kNumThreads);
std::vector<std::thread> threads;
threads.reserve(kNumThreads);
for (unsigned t = 0; t < kNumThreads; ++t) {
threads.emplace_back([&gate, t]() {
if (t % 2 == 0) {
unsigned sec = t / 2;
std::printf("th%02u sleep %us\n", t, sec);
std::this_thread::sleep_for(std::chrono::seconds(sec));
}
std::printf("th%02u at gate\n", t);
gate.arrive_and_wait();
std::printf("th%02u finished\n", t);
});
}
for (auto& th : threads) {
th.join();
}
return 0;
}
|