-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprintZeroEvenOdd.cpp
More file actions
47 lines (42 loc) · 1.03 KB
/
printZeroEvenOdd.cpp
File metadata and controls
47 lines (42 loc) · 1.03 KB
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
// Source: https://leetcode.com/problems/print-zero-even-odd/
// Author: Miao Zhang
// Date: 2021-04-12
class ZeroEvenOdd {
private:
int n;
std::mutex mzero_;
std::mutex meven_;
std::mutex modd_;
public:
ZeroEvenOdd(int n) {
this->n = n;
meven_.lock();
modd_.lock();
}
// printNumber(x) outputs "x", where x is an integer.
void zero(function<void(int)> printNumber) {
for (int i = 0; i < n; i++) {
mzero_.lock();
printNumber(0);
if (i % 2 == 0) {
modd_.unlock();
} else {
meven_.unlock();
}
}
}
void even(function<void(int)> printNumber) {
for (int i = 2; i <= n; i +=2) {
meven_.lock();
printNumber(i);
mzero_.unlock();
}
}
void odd(function<void(int)> printNumber) {
for (int i = 1; i <= n; i +=2) {
modd_.lock();
printNumber(i);
mzero_.unlock();
}
}
};