-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOneTwoThree.cpp
More file actions
87 lines (71 loc) · 1.4 KB
/
OneTwoThree.cpp
File metadata and controls
87 lines (71 loc) · 1.4 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
84
85
86
87
#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <mutex>
#include <functional>
#include <condition_variable>
#include <atomic>
using namespace std;
bool pFirst = true;
bool pSecond = true;
bool pThird = true;
condition_variable cv;
mutex mtx;
void printOne(int n)
{
for (int i = 0; i < n; i++)
{
unique_lock<mutex> ulock(mtx);
cv.wait(ulock, [&]
{ return true == pFirst; });
cout
<< "first";
pFirst = false;
pSecond = true;
ulock.unlock();
cv.notify_all();
}
}
void printTwo(int n)
{
for (int i = 0; i < n; i++)
{
unique_lock<mutex> ulock(mtx);
cv.wait(ulock, [&]
{ return true == pSecond; });
cout
<< "second";
pSecond = false;
pThird = true;
ulock.unlock();
cv.notify_all();
}
}
void printThree(int n)
{
for (int i = 0; i < n; i++)
{
unique_lock<mutex> ulock(mtx);
cv.wait(ulock, [&]
{ return true == pThird; });
cout
<< "third";
pThird = false;
pFirst = true;
ulock.unlock();
cv.notify_all();
}
}
int main()
{
int n = 3;
thread t1(printOne, n);
thread t2(printTwo, n);
thread t3(printThree, n);
t1.join();
t2.join();
t3.join();
cout << endl;
return 0;
}