-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample.cpp
More file actions
82 lines (66 loc) · 2.01 KB
/
Example.cpp
File metadata and controls
82 lines (66 loc) · 2.01 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
/**
* \file Example.cpp
* \brief
*
* \todo
*/
// cpp11_cond_variable_example.cpp
// g++ -std=c++11 condition_variable.cpp -o main -lpthread
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//-------------------------------------------------------------------------------------------------
bool isReady;
std::mutex mutex;
std::condition_variable condvar;
std::queue<int> messageQ;
//-------------------------------------------------------------------------------------------------
void Producer()
{
std::cout << "::: Producer :::" << std::endl;
for (auto x = 0; x < 10; ++ x) {
std::lock_guard<std::mutex> guard(mutex);
std::cout << "Producing message: " << x << " th" << std::endl;
messageQ.push(x);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
{
std::lock_guard<std::mutex> guard(mutex);
isReady = true;
}
std::cout << "::: Producer has completed :::" << std::endl;
condvar.notify_one();
}
//-------------------------------------------------------------------------------------------------
void Consumer()
{
{
std::unique_lock<std::mutex> ulock(mutex);
condvar.wait(ulock,
[]{
return isReady;
});
}
std::cout << "\n\n::: Consumer is ready to get message :::" << std::endl;
while ( !messageQ.empty() ) {
std::lock_guard<std::mutex> guard(mutex);
int i = messageQ.front();
std::cout << "Consuming message: " << i << " th" << std::endl;
messageQ.pop();
}
if ( !messageQ.empty() ) {
std::cout << "There are still messages remained from producer" << std::endl;
} else {
std::cout << "All messages from producer has been processed" << std::endl;
}
}
//-------------------------------------------------------------------------------------------------
int main()
{
auto t1 = std::async(std::launch::async, Producer);
auto t2 = std::async(std::launch::async, Consumer);
t1.get();
t2.get();
return 0;
}
//-------------------------------------------------------------------------------------------------