-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMutex_01_Simple.cpp
More file actions
77 lines (60 loc) · 1.97 KB
/
Mutex_01_Simple.cpp
File metadata and controls
77 lines (60 loc) · 1.97 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
// ===========================================================================
// Mutual Exclusion Demonstration // Mutex_01_Simple.cpp
// ===========================================================================
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
namespace SimpleMutexDemo
{
class Counter
{
private:
const std::size_t NumIterations{ 100000 };
int m_id{};
static std::mutex s_mutex;
// Note: remove static
// a) Line above
// b) put 'std::mutex Counter::s_mutex{};' into comments
// c) add 'mutable' to s_mutex declaration
public:
Counter(int id) : m_id{ id } {}
void run() const {
for (std::size_t i{}; i != NumIterations; ++i)
{
{
// <== remove comment from next line to demonstrate scattered output
// std::lock_guard<std::mutex> guard{ s_mutex };
// std::lock_guard guard{ s_mutex }; // C++ 17 (automatic type deduction)
std::cout << "Counter " << m_id << ": i=" << i << "\n";
}
// just to force rescheduling the execution of the threads
std::this_thread::sleep_for(std::chrono::milliseconds{ 1 });
}
}
};
std::mutex Counter::s_mutex{};
}
void test()
{
using namespace SimpleMutexDemo;
Counter counter1{ 1 };
Counter counter2{ 2 };
Counter counter3{ 3 };
// run 3 threads ...
std::thread t1{ &Counter::run, &counter1 };
std::thread t2{ &Counter::run, &counter2 };
std::thread t3{ &Counter::run, &counter3 };
// wait for threads to finish
t1.join();
t2.join();
t3.join();
}
void test_simple_mutex()
{
using namespace SimpleMutexDemo;
test();
}
// ===========================================================================
// End-of-File
// ===========================================================================