forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
print-in-order.cpp
110 lines (95 loc) · 2.47 KB
/
print-in-order.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Time: O(n)
// Space: O(1)
class Foo {
public:
Foo() {
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
p1_.set_value();
}
void second(function<void()> printSecond) {
p1_.get_future().wait();
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
p2_.set_value();
}
void third(function<void()> printThird) {
p2_.get_future().wait();
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
private:
promise<void> p1_;
promise<void> p2_;
};
// Time: O(n)
// Space: O(1)
class Foo2 {
public:
Foo2() {
}
void first(function<void()> printFirst) {
{
unique_lock<mutex> l(m_);
has_first_ = true;
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
}
cv_.notify_all();
}
void second(function<void()> printSecond) {
{
unique_lock<mutex> l(m_);
cv_.wait(l, [this]() { return has_first_; });
has_second_ = true;
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
}
cv_.notify_all();
}
void third(function<void()> printThird) {
{
unique_lock<mutex> l(m_);
cv_.wait(l, [this]() { return has_second_; });
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
cv_.notify_all();
}
private:
bool has_first_ = false;
bool has_second_ = false;
mutex m_;
condition_variable cv_;
};
// Time: O(n)
// Space: O(1)
class Foo3 {
public:
Foo3() {
m1_.lock();
m2_.lock();
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
m1_.unlock();
}
void second(function<void()> printSecond) {
m1_.lock();
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
m1_.unlock();
m2_.unlock();
}
void third(function<void()> printThird) {
m2_.lock();
// printThird() outputs "third". Do not change or remove this line.
printThird();
m2_.unlock();
}
private:
mutex m1_, m2_;
};