-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1117.BuildingH2O.cpp
More file actions
36 lines (31 loc) · 859 Bytes
/
1117.BuildingH2O.cpp
File metadata and controls
36 lines (31 loc) · 859 Bytes
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
class H2O {
public:
H2O() {}
void hydrogen(function<void()> releaseHydrogen) {
const int index = m_hydrogenCount.fetch_add(1);
const int waitIndex = ((index / 2) * 3) + (index % 2);
orderWait(waitIndex);
releaseHydrogen();
orderFinish(waitIndex);
}
void oxygen(function<void()> releaseOxygen) {
const int index = m_oxygenCount.fetch_add(1);
const int waitIndex = (index * 3) + 2;
orderWait(waitIndex);
releaseOxygen();
orderFinish(waitIndex);
}
private:
void orderWait(const int order) {
int current;
while ((current = m_order.load()) != order)
m_order.wait(current);
}
void orderFinish(const int order) {
m_order = order + 1;
m_order.notify_all();
}
private:
std::atomic<int> m_oxygenCount, m_hydrogenCount;
std::atomic<int> m_order;
};