-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlternateFooBar.cpp
More file actions
61 lines (54 loc) · 1.24 KB
/
AlternateFooBar.cpp
File metadata and controls
61 lines (54 loc) · 1.24 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
#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <mutex>
#include <functional>
#include <condition_variable>
#include <atomic>
using namespace std;
bool printedFoo = false;
condition_variable cv;
mutex mtx;
void printFoo(int n)
{
for (int i = 0; i < n; i++)
{
unique_lock<mutex> ulock(mtx);
// Sleep until printedFoo becomes false.
// or wakeup when printedFoo = false
cv.wait(ulock, [&]
{ return printedFoo == false; });
cout
<< "foo";
printedFoo = true;
ulock.unlock(); // without this program works correctly
// but unlocking early helps other thread to wake up immediately
// so there is less lock contention
cv.notify_one();
}
}
void printBar(int n)
{
for (int i = 0; i < n; i++)
{
unique_lock<mutex> ulock(mtx);
// wakeup when printedFoo becomes true
cv.wait(ulock, [&]
{ return printedFoo == true; });
cout
<< "bar";
printedFoo = false;
ulock.unlock();
cv.notify_one();
}
}
int main()
{
int n = 10;
thread t1(printFoo, n);
thread t2(printBar, n);
t1.join();
t2.join();
return 0;
}