Skip to content

Commit fc5d53c

Browse files
authored
Create fizz-buzz-multithreaded.cpp
1 parent 5c36ab4 commit fc5d53c

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

C++/fizz-buzz-multithreaded.cpp

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class FizzBuzz {
5+
public:
6+
FizzBuzz(int n) : n_(n) {
7+
}
8+
9+
// printFizz() outputs "fizz".
10+
void fizz(function<void()> printFizz) {
11+
for (int i = 1; i <= n_; ++i) {
12+
{
13+
unique_lock<mutex> l(m_);
14+
wait_.wait(l, [this]() { return curr_ % 4 == 0; });
15+
++curr_;
16+
if (i % 3 == 0 && i % 5 != 0) {
17+
printFizz();
18+
}
19+
}
20+
wait_.notify_all();
21+
}
22+
}
23+
24+
// printBuzz() outputs "buzz".
25+
void buzz(function<void()> printBuzz) {
26+
for (int i = 1; i <= n_; ++i) {
27+
{
28+
unique_lock<mutex> l(m_);
29+
wait_.wait(l, [this]() { return curr_ % 4 == 1; });
30+
++curr_;
31+
if (i % 3 != 0 && i % 5 == 0) {
32+
printBuzz();
33+
}
34+
}
35+
wait_.notify_all();
36+
}
37+
}
38+
39+
// printFizzBuzz() outputs "fizzbuzz".
40+
void fizzbuzz(function<void()> printFizzBuzz) {
41+
for (int i = 1; i <= n_; ++i) {
42+
{
43+
unique_lock<mutex> l(m_);
44+
wait_.wait(l, [this]() { return curr_ % 4 == 2; });
45+
++curr_;
46+
if (i % 3 == 0 && i % 5 == 0) {
47+
printFizzBuzz();
48+
}
49+
}
50+
wait_.notify_all();
51+
}
52+
}
53+
54+
// printNumber(x) outputs "x", where x is an integer.
55+
void number(function<void(int)> printNumber) {
56+
for (int i = 1; i <= n_; ++i) {
57+
{
58+
unique_lock<mutex> l(m_);
59+
wait_.wait(l, [this]() { return curr_ % 4 == 3; });
60+
++curr_;
61+
if (i % 3 != 0 && i % 5 != 0) {
62+
printNumber(i);
63+
}
64+
}
65+
wait_.notify_all();
66+
}
67+
}
68+
69+
private:
70+
int n_;
71+
int curr_ = 0;
72+
mutex m_;
73+
condition_variable wait_;
74+
};

0 commit comments

Comments
 (0)