-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuildingH2O.cpp
53 lines (43 loc) · 996 Bytes
/
buildingH2O.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
// Source: https://leetcode.com/problems/building-h2o/
// Author: Miao Zhang
// Date: 2021-04-12
class Semaphore {
public:
Semaphore(int s): s_(s) {}
void P(int d = 1) {
unique_lock<mutex> lock(m_);
while (s_ < d) {
cv_.wait(lock);
}
s_ -= d;
}
void V(int d = 1) {
unique_lock<mutex> lock(m_);
s_ += d;
cv_.notify_all();
}
private:
std::mutex m_;
condition_variable cv_;
int s_;
};
class H2O {
public:
H2O(): s_h_(2), s_o_(2) {
}
void hydrogen(function<void()> releaseHydrogen) {
s_h_.P();
// releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen();
s_o_.V();
}
void oxygen(function<void()> releaseOxygen) {
s_o_.P(2);
// releaseOxygen() outputs "O". Do not change or remove this line.
releaseOxygen();
s_h_.V(2);
}
private:
Semaphore s_h_;
Semaphore s_o_;
};