-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFizz_Buzz_Multithreaded.cpp
More file actions
83 lines (76 loc) · 1.98 KB
/
Fizz_Buzz_Multithreaded.cpp
File metadata and controls
83 lines (76 loc) · 1.98 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
73
74
75
76
77
78
79
80
81
82
83
//https://leetcode.com/problems/fizz-buzz-multithreaded/
/*
Think about what need to be synchronized, and what should be inside the critical section. So in this problem, the read/update
of n should be inside the critical section and get synchronized. Therefore we can use one mutex to protect it.
*/
class FizzBuzz {
private:
int n;
int counter;
mutex m;
public:
FizzBuzz(int n) {
this->n = n;
counter = 1;
}
// printFizz() outputs "fizz".
void fizz(function<void()> printFizz) {
while (1){
m.lock();
if (counter > n){
m.unlock();
return;
}
if (counter % 3 == 0 && counter % 5 != 0){
printFizz();
counter++;
}
m.unlock();
}
}
// printBuzz() outputs "buzz".
void buzz(function<void()> printBuzz) {
while (1){
m.lock();
if (counter > n){
m.unlock();
return;
}
if (counter % 3 != 0 && counter % 5 == 0){
printBuzz();
counter++;
}
m.unlock();
}
}
// printFizzBuzz() outputs "fizzbuzz".
void fizzbuzz(function<void()> printFizzBuzz) {
while (1){
m.lock();
if (counter > n){
m.unlock();
return;
}
if (counter % 3 == 0 && counter % 5 == 0){
printFizzBuzz();
counter++;
}
m.unlock();
}
}
// printNumber(x) outputs "x", where x is an integer.
void number(function<void(int)> printNumber) {
while (1){
m.lock();
if (counter > n){
m.unlock();
return;
}
if (counter % 3 != 0 && counter % 5 != 0){
printNumber(counter);
counter++;
}
m.unlock();
}
}
};