-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1114. Print in Order_atomic.cc
59 lines (51 loc) · 1.25 KB
/
1114. Print in Order_atomic.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
53
54
55
56
57
58
59
// Using atomic variable, condition variable and mutex
// TC: O(1)
// SC: O(1)
class Foo {
private:
atomic<int> turn = 1;
mutex m;
condition_variable cv;
public:
Foo() {
}
void first(function<void()> printFirst) {
unique_lock<mutex> um(m);
// printFirst() outputs "first". Do not change or remove this line.
cv.wait(um, [&](){
return turn == 1;
});
printFirst();
turn = 2;
cv.notify_all();
}
void second(function<void()> printSecond) {
unique_lock<mutex> um(m);
// printSecond() outputs "second". Do not change or remove this line.
cv.wait(um, [&](){
return turn == 2;
});
printSecond();
turn = 3;
cv.notify_all();
}
void third(function<void()> printThird) {
unique_lock<mutex> um(m);
// printThird() outputs "third". Do not change or remove this line.
cv.wait(um, [&](){
return turn == 3;
});
printThird();
turn = 1;
cv.notify_all();
}
void printFirst(){
cout << "First";
}
void printSecond(){
cout << "Second";
}
void printThird(){
cout << "Third";
}
};