-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCondition_Variable_01_Simple.cpp
More file actions
83 lines (60 loc) · 1.94 KB
/
Condition_Variable_01_Simple.cpp
File metadata and controls
83 lines (60 loc) · 1.94 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
// ===========================================================================
// Condition_Variable_01_Simple.cpp // Condition Variable
// ===========================================================================
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include "../Logger/Logger.h"
namespace SimpleConditionVariableDemo01
{
static std::mutex mutex{};
static std::condition_variable condition{};
static bool data{ false };
static void consume()
{
Logger::log(std::cout, "Function Consume:");
{
std::unique_lock<std::mutex> guard{ mutex };
condition.wait(
guard,
[] () {
Logger::log(std::cout, " ... check for data being present: ", data == true);
return data == true;
}
);
}
Logger::log(std::cout, "Data has been consumed ...");
Logger::log(std::cout, "Done Thread ");
}
static void produce()
{
Logger::log(std::cout, "Function Produce:");
// put into comment ... or not
std::this_thread::sleep_for(std::chrono::milliseconds{ 5000 });
{
std::lock_guard<std::mutex> guard{ mutex };
data = true;
}
Logger::log(std::cout, "Data has been produced ...");
condition.notify_one();
Logger::log(std::cout, "Done Thread ");
}
static void test()
{
Logger::log(std::cout, "Function Main:");
std::thread t1{ produce };
std::thread t2{ consume };
t1.join();
t2.join();
Logger::log(std::cout, "Done Main.");
}
}
void test_simple_condition_variable_01()
{
using namespace SimpleConditionVariableDemo01;
test();
}
// ===========================================================================
// End-of-File
// ===========================================================================