-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex2.cpp
73 lines (65 loc) · 1.79 KB
/
mutex2.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
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std;
mutex coutMutex;
struct Worker {
// storing reference
string name;
public:
Worker(string n): name(n) {};
void operator() () {
for (unsigned int j = 0; j <= 3; j++) {
this_thread::sleep_for(chrono::milliseconds(200));
coutMutex.lock();
cout << name << ": " << "Work " << j << " done!!!" << endl;
coutMutex.unlock();
}
}
};
int main() {
cout << "Let's start working!!" << endl;
thread a = thread(Worker("A"));
thread b = thread(Worker("B"));
thread c = thread(Worker("C"));
thread d = thread(Worker("D"));
thread e = thread(Worker("E"));
thread f = thread(Worker("F"));
a.join();
b.join();
c.join();
d.join();
e.join();
f.join();
cout << "Let's go home!!" << endl;
/* We use mutex to lock the cout operation. Still the problem is to remember to lock and unlock the mutex. We solve this through the lock_guard. It is defined in the mutex header file.
Let's start working!!
A: Work 0 done!!!
F: Work 0 done!!!
C: Work 0 done!!!
E: Work 0 done!!!
B: Work 0 done!!!
D: Work 0 done!!!
A: Work 1 done!!!
F: Work 1 done!!!
D: Work 1 done!!!
C: Work 1 done!!!
E: Work 1 done!!!
B: Work 1 done!!!
F: Work 2 done!!!
A: Work 2 done!!!
D: Work 2 done!!!
B: Work 2 done!!!
C: Work 2 done!!!
E: Work 2 done!!!
F: Work 3 done!!!
A: Work 3 done!!!
D: Work 3 done!!!
B: Work 3 done!!!
C: Work 3 done!!!
E: Work 3 done!!!
Let's go home!!
*/
return 0;
}