-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathdemo21b-condition-variable.cpp
More file actions
77 lines (54 loc) · 1.43 KB
/
Copy pathdemo21b-condition-variable.cpp
File metadata and controls
77 lines (54 loc) · 1.43 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
/*
CONDITION VARIABLES
*/
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
std::mutex mut;
std::condition_variable conditionVar;
int counter = 0;
constexpr int COUNT_HALT_01 = 3;
constexpr int COUNT_HALT_02 = 6;
constexpr int COUNT_DONE = 10;
// Write numbers 1-3 and 8-10 as permitted by egg()
void foo() {
for (;;) {
// Lock mutex and then wait for signal to relase mutex
std::unique_lock<std::mutex> lk(mut);
// Wait while egg() operates on counter,
// Mutex unlocked if condition variable in egg() signaled
conditionVar.wait(lk);
++counter;
cout << "foo counter = " << counter << endl;
if (counter >= COUNT_DONE) {
return;
}
}
}
// Write numbers 4-7
void egg() {
for (;;) {
std::unique_lock<std::mutex> lk(mut);
if (counter < COUNT_HALT_01 || counter > COUNT_HALT_02) {
// Signal to free waiting thread by freeing the mutex
// Note: foo() is now permitted to modify "counter"
conditionVar.notify_one();
}
else {
++counter;
cout << "egg counter = " << counter << endl;
}
if (counter >= COUNT_DONE) {
return;
}
}
}
int main() {
auto thFoo = std::thread(&foo);
auto thEgg = std::thread(&egg);
thFoo.join();
thEgg.join();
return 0;
}