-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmutex.cpp
118 lines (110 loc) · 2.33 KB
/
mutex.cpp
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <thread>
#include <mutex>
#define CORRECT
int cur = 1;
int n = 15;
std::mutex mtx;
//from leetcode: https://leetcode.com/problems/fizz-buzz-multithreaded/
//ref: http://www.cplusplus.com/reference/mutex/mutex/lock/
//g++ mutex.cpp -std=c++11 -lpthread
void fizz(){
#ifndef CORRECT
//this will give wrong, unpredictable result
while(cur <= n){
if(cur % 3 == 0 && cur % 15 != 0){
mtx.lock();
std::cout << " fizz";
cur++;
mtx.unlock();
}
}
#else
//this will always gives correct result
while(true){
mtx.lock();
if(cur <= n && cur % 3 == 0 && cur % 15 != 0){
std::cout << " fizz";
cur++;
}
mtx.unlock();
if(cur > n) break;
}
#endif
}
void buzz(){
#ifndef CORRECT
while(cur <= n){
if(cur % 5 == 0 && cur % 15 != 0){
mtx.lock();
std::cout << " buzz";
cur++;
mtx.unlock();
}
}
#else
while(true){
mtx.lock();
if(cur <= n && cur % 5 == 0 && cur % 15 != 0){
std::cout << " buzz";
cur++;
}
mtx.unlock();
if(cur > n) break;
}
#endif
}
void fizzbuzz(){
#ifndef CORRECT
while(cur <= n){
if(cur % 15 == 0){
mtx.lock();
std::cout << " fizzbuzz";
cur++;
mtx.unlock();
}
}
#else
while(true){
mtx.lock();
if(cur <= n && cur % 15 == 0){
std::cout << " fizzbuzz";
cur++;
}
mtx.unlock();
if(cur > n) break;
}
#endif
}
void num(){
#ifndef CORRECT
while(cur <= n){
if(cur % 3 != 0 && cur % 5 != 0){
mtx.lock();
std::cout << " " << cur;
cur++;
mtx.unlock();
}
}
#else
while(true){
mtx.lock();
if(cur <= n && cur % 3 != 0 && cur % 5 != 0){
std::cout << " " << cur;
cur++;
}
mtx.unlock();
if(cur > n) break;
}
#endif
}
int main(){
std::thread threads[4];
threads[0] = std::thread(fizz);
threads[1] = std::thread(buzz);
threads[2] = std::thread(fizzbuzz);
threads[3] = std::thread(num);
for (auto& th : threads) th.join();
std::cout << std::endl;
return 0;
}