-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCondition_Variable_02_Simple.cpp
More file actions
62 lines (45 loc) · 1.64 KB
/
Condition_Variable_02_Simple.cpp
File metadata and controls
62 lines (45 loc) · 1.64 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
// ===========================================================================
// Condition_Variable_02_Simple.cpp // Condition Variable
// ===========================================================================
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include "../Logger/Logger.h"
namespace SimpleConditionVariableDemo02
{
static constexpr long NumIterations{ 5 };
static std::mutex mutex;
static std::condition_variable condition;
static void function()
{
std::thread::id tid{ std::this_thread::get_id() };
Logger::log(std::cout, "TID: ", tid);
std::unique_lock<std::mutex> guard{ mutex };
condition.wait(guard);
Logger::log(std::cout, "Done Thread ", tid);
}
static void test()
{
std::thread::id mainTID{ std::this_thread::get_id() };
Logger::log(std::cout, "Begin Main: ", mainTID);
std::thread t1{ function };
std::thread t2{ function };
std::this_thread::sleep_for(std::chrono::seconds{ 2 });
condition.notify_one(); // demonstrate either this line
// condition.notify_all(); // or this line
std::this_thread::sleep_for(std::chrono::seconds{ 2 });
condition.notify_one(); // and this line
t1.join();
t2.join();
Logger::log(std::cout, "Done Main.");
}
}
void test_simple_condition_variable_02()
{
using namespace SimpleConditionVariableDemo02;
test();
}
// ===========================================================================
// End-of-File
// ===========================================================================