-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprint_zero_even_odd.cpp
More file actions
72 lines (66 loc) 路 1.78 KB
/
Copy pathprint_zero_even_odd.cpp
File metadata and controls
72 lines (66 loc) 路 1.78 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
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
// https://leetcode.com/problems/print-zero-even-odd/
class ZeroEvenOdd {
private:
int n;
int len;
int idx;
int num;
mutex mtxz, mtxe, mtxo;
condition_variable cv;
public:
ZeroEvenOdd(int n) {
this->n = n;
this->len = 2*n;
this->idx = 0;
this->num = 1;
// acquire these two locks now
// leave the zero lock unacquired to avoid deadlock
// and also because we want the thread to start with that
mtxe.lock();
mtxo.lock();
}
void releaseLockIfPossible() {
idx++;
if(idx >= len) {
mtxz.unlock();
mtxe.unlock();
mtxo.unlock();
} else if( idx % 2 == 0){
mtxz.unlock();
} else if(idx % 2 == 1 && num % 2 == 1) {
mtxo.unlock();
} else if (idx % 2 == 1 && num % 2 == 0) {
mtxe.unlock();
}
}
// printNumber(x) outputs "x", where x is an integer.
void zero(function<void(int)> printNumber) {
while(idx < len) {
mtxz.lock();
if (idx >= len) break;
printNumber(0);
cout << 0 << flush;
releaseLockIfPossible();
}
}
void even(function<void(int)> printNumber) {
while(idx < len) {
mtxe.lock();
if (idx >= len) break;
printNumber(num);
cout << num << flush;
num++;
releaseLockIfPossible();
}
}
void odd(function<void(int)> printNumber) {
while(idx < len) {
mtxo.lock();
if (idx >= len) break;
printNumber(num);
cout << num << flush;
num++;
releaseLockIfPossible();
}
}
};