-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasics.cpp
More file actions
58 lines (51 loc) · 1.44 KB
/
Basics.cpp
File metadata and controls
58 lines (51 loc) · 1.44 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
/**
* \file Basics.cpp
* \brief
*
* \todo
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//-------------------------------------------------------------------------------------------------
std::deque<int> q;
std::mutex mu;
std::condition_variable cond;
//-------------------------------------------------------------------------------------------------
// Using conditional variable and mutex
void function_1()
{
int count = 10;
while (count > 0) {
std::unique_lock<std::mutex> locker(mu);
q.push_front(count);
locker.unlock();
cond.notify_one(); // Notify one waiting thread, if there is one.
std::this_thread::sleep_for(std::chrono::seconds(1));
count--;
}
}
//-------------------------------------------------------------------------------------------------
void function_2()
{
int data = 0;
while (data != 1) {
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker, [](){ return !q.empty();} ); // Unlock mu and wait to be notified
// relock mu
data = q.back();
q.pop_back();
locker.unlock();
std::cout << "t2 got a value from t1: " << data << std::endl;
}
}
//-------------------------------------------------------------------------------------------------
int main()
{
std::thread t1(function_1);
std::thread t2(function_2);
t1.join();
t2.join();
return 0;
}
//-------------------------------------------------------------------------------------------------