-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprint-zero-even-odd.cpp
More file actions
68 lines (56 loc) · 1.59 KB
/
print-zero-even-odd.cpp
File metadata and controls
68 lines (56 loc) · 1.59 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
class ZeroEvenOdd {
private:
int n;
public:
ZeroEvenOdd(int n) {
this->n = n;
}
// printNumber(x) outputs "x", where x is an integer.
void zero(function<void(int)> printNumber) {
// ??????while????ThreadA????zero??
while(1){
{
unique_lock<mutex> lk(_mu);
_cond.wait(lk,[this](){return print0;});
if(i<=n) printNumber(0);
print0=printodd=printeven=false;
if(i%2==1) printodd=true;
else printeven=true;
}
_cond.notify_all();
if(i>n) break;
}
}
// ??
void even(function<void(int)> printNumber) {
while(1){
{
unique_lock<mutex> lk(_mu);
_cond.wait(lk,[this](){return printeven;});
if(i<=n) printNumber(i++);
print0=true;
printodd=printeven=false;
}
_cond.notify_all();
if(i>n) break;
}
}
// ??
void odd(function<void(int)> printNumber) {
while(1){
{
unique_lock<mutex> lk(_mu);
_cond.wait(lk,[this](){return printodd;});
if(i<=n) printNumber(i++);
print0=true;
printodd=printeven=false;
}
_cond.notify_all();
if(i>n) break;
}
}
mutex _mu;
condition_variable _cond;
int i=1;
bool print0=true,printeven=false,printodd=false;
};