forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
building-h2o.cpp
108 lines (95 loc) · 2.29 KB
/
building-h2o.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
// Time: O(n)
// Space: O(1)
class H2O {
public:
H2O() {
}
void hydrogen(function<void()> releaseHydrogen) {
unique_lock<mutex> l(m_);
releaseHydrogen_ = releaseHydrogen;
++nH_;
output();
}
void oxygen(function<void()> releaseOxygen) {
unique_lock<mutex> l(m_);
releaseOxygen_ = releaseOxygen;
++nO_;
output();
}
private:
void output() {
while (nH_ >= 2 && nO_ >= 1) {
nH_ -= 2;
nO_ -= 1;
releaseHydrogen_();
releaseHydrogen_();
releaseOxygen_();
}
}
int nH_ = 0;
int nO_ = 0;
function<void()> releaseHydrogen_ = nullptr;
function<void()> releaseOxygen_ = nullptr;
mutex m_;
};
// Time: O(n)
// Space: O(1)
class H2O2 {
public:
H2O2() {
}
void hydrogen(function<void()> releaseHydrogen) {
{
unique_lock<mutex> l(m_);
cv_.wait(l, [this]() { return (nH_ + 1) - 2 * nO_ <= 2; });
++nH_;
// releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen();
}
cv_.notify_all();
}
void oxygen(function<void()> releaseOxygen) {
{
unique_lock<mutex> l(m_);
cv_.wait(l, [this]() { return 2 * (nO_ + 1) - nH_ <= 2; });
++nO_;
// releaseOxygen() outputs "O". Do not change or remove this line.
releaseOxygen();
}
cv_.notify_all();
}
private:
int nH_ = 0;
int nO_ = 0;
mutex m_;
condition_variable cv_;
};
// Time: O(n)
// Space: O(1)
// this is much like single thread execution
class H2O3 {
public:
H2O3(): curr_(2) {
m2_.lock();
}
void hydrogen(function<void()> releaseHydrogen) {
m1_.lock();
// releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen();
if (--curr_) {
m1_.unlock();
} else {
m2_.unlock();
}
}
void oxygen(function<void()> releaseOxygen) {
m2_.lock();
// releaseOxygen() outputs "O". Do not change or remove this line.
releaseOxygen();
curr_ = 2;
m1_.unlock();
}
private:
int curr_ = 0;
mutex m1_, m2_;
};