-
Notifications
You must be signed in to change notification settings - Fork 0
/
print-in-order.cc
52 lines (44 loc) · 1.11 KB
/
print-in-order.cc
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
#include <algorithm>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
class Foo {
public:
Foo() {}
void first(function<void()> &&fn) {
fn();
flags_[0] = true;
cv_.notify_all();
}
void second(function<void()> &&fn) {
unique_lock<mutex> lock(mtx_);
cv_.wait(lock, [this] { return flags_[0]; });
fn();
flags_[1] = true;
cv_.notify_all();
}
void third(function<void()> &&fn) {
unique_lock<mutex> lock(mtx_);
cv_.wait(lock, [this] { return flags_[1]; });
fn();
}
private:
mutex mtx_;
condition_variable cv_;
bool flags_[2]{false, false};
};
int main(int argc, char const *argv[]) {
Foo foo;
auto one = [] { cout << "one"; };
auto two = [] { cout << "two"; };
auto three = [] { cout << "three"; };
thread thd3([&] { foo.third(three); });
thread thd1([&] { foo.first(one); });
thread thd2([&] { foo.second(two); });
thd3.join();
thd1.join();
thd2.join();
}