-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathExample_LockingStrategies.cpp
More file actions
55 lines (38 loc) · 1.48 KB
/
Example_LockingStrategies.cpp
File metadata and controls
55 lines (38 loc) · 1.48 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
// ===========================================================================
// Examples_LockingStrategies.cpp // `std::defer_lock` vs `std::adopt_lock`
// ===========================================================================
#include <algorithm>
#include <iostream>
#include <mutex>
#include <thread>
// https://medium.com/@back_to_basics/c-11-locking-strategy-adopt-lock-and-defer-lock-eeedf76a2689
namespace Locking_Strategies
{
std::mutex g_mutex1{};
std::mutex g_mutex2{};
static void example01() {
// calling thread locks the mutexes
std::lock(g_mutex1, g_mutex2);
std::lock_guard<std::mutex> lock1{ g_mutex1, std::adopt_lock };
std::lock_guard<std::mutex> lock2{ g_mutex2, std::adopt_lock };
// access shared data protected by g_mutex1 and g_mutex2
// release of mutexes
}
static void example02() {
std::unique_lock<std::mutex> lock1{ g_mutex1, std::defer_lock };
std::unique_lock<std::mutex> lock2{ g_mutex2, std::defer_lock };
// mutexes are locked now
std::lock(lock1, lock2);
// access shared data protected by the g_mutex1 and g_mutex2
// release of mutexes
}
}
void example_locking_strategies()
{
using namespace Locking_Strategies;
example01();
example02();
}
// ===========================================================================
// End-of-File
// ===========================================================================