forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
print-zero-even-odd.cpp
95 lines (85 loc) · 2.13 KB
/
print-zero-even-odd.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
// Time: O(n)
// Space: O(1)
class ZeroEvenOdd {
public:
ZeroEvenOdd(int n) : n_(n) {
}
// printNumber(x) outputs "x", where x is an integer.
void zero(function<void(int)> printNumber) {
for (int i = 0; i < n_; ++i) {
{
unique_lock<mutex> l(m_);
wait_.wait(l, [this]() { return curr_ % 2 == 0; });
++curr_;
printNumber(0);
}
wait_.notify_all();
}
}
void even(function<void(int)> printNumber) {
for (int i = 2; i <= n_; i += 2) {
{
unique_lock<mutex> l(m_);
wait_.wait(l, [this]() { return curr_ % 4 == 3; });
++curr_;
printNumber(i);
}
wait_.notify_all();
}
}
void odd(function<void(int)> printNumber) {
for (int i = 1; i <= n_; i += 2) {
{
unique_lock<mutex> l(m_);
wait_.wait(l, [this]() { return curr_ % 4 == 1; });
++curr_;
printNumber(i);
}
wait_.notify_all();
}
}
private:
int n_;
int curr_ = 0;
mutex m_;
condition_variable wait_;
};
// Time: O(n)
// Space: O(1)
class ZeroEvenOdd2 {
public:
ZeroEvenOdd2(int n) : n_(n) {
m2_.lock();
m3_.lock();
}
// printNumber(x) outputs "x", where x is an integer.
void zero(function<void(int)> printNumber) {
for (int i = 0; i < n_; ++i) {
m1_.lock();
printNumber(0);
if (++curr_ % 2) {
m2_.unlock();
} else {
m3_.unlock();
}
}
}
void even(function<void(int)> printNumber) {
for (int i = 2; i <= n_; i += 2) {
m3_.lock();
printNumber(curr_);
m1_.unlock();
}
}
void odd(function<void(int)> printNumber) {
for (int i = 1; i <= n_; i += 2) {
m2_.lock();
printNumber(curr_);
m1_.unlock();
}
}
private:
int n_;
int curr_ = 0;
mutex m1_, m2_, m3_;
};