-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfizzBuzzMultithreaded.cpp
More file actions
78 lines (67 loc) · 1.76 KB
/
fizzBuzzMultithreaded.cpp
File metadata and controls
78 lines (67 loc) · 1.76 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
// Source: https://leetcode.com/problems/fizz-buzz-multithreaded/
// Author: Miao Zhang
// Date: 2021-04-16
class Semaphore {
public:
Semaphore (int count = 0): count_(count) {}
inline void notify() {
unique_lock<std::mutex> lock(mtx_);
count_++;
cv_.notify_one();
}
inline void wait() {
unique_lock<std::mutex> lock(mtx_);
while (count_ == 0) cv_.wait(lock);
count_--;
}
private:
mutex mtx_;
condition_variable cv_;
int count_;
};
class FizzBuzz {
private:
int n;
Semaphore sn;
Semaphore s3;
Semaphore s5;
Semaphore s15;
public:
FizzBuzz(int n): n(n), sn(1), s3(0), s5(0), s15(0) {
}
// printFizz() outputs "fizz".
void fizz(function<void()> printFizz) {
for (int i = 3; i <= n; i += 3) {
if (i % 5 == 0) continue;
s3.wait();
printFizz();
sn.notify();
}
}
// printBuzz() outputs "buzz".
void buzz(function<void()> printBuzz) {
for (int i = 5; i <= n; i += 5) {
if (i % 3 == 0) continue;
s5.wait();
printBuzz();
sn.notify();
}
}
// printFizzBuzz() outputs "fizzbuzz".
void fizzbuzz(function<void()> printFizzBuzz) {
for (int i = 15; i <= n; i += 15) {
s15.wait();
printFizzBuzz();
sn.notify();
}
}
// printNumber(x) outputs "x", where x is an integer.
void number(function<void(int)> printNumber) {
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) { s15.notify(); sn.wait(); }
else if (i % 5 == 0) { s5.notify(); sn.wait(); }
else if (i % 3 == 0) { s3.notify(); sn.wait(); }
else { printNumber(i); }
}
}
};