-
Notifications
You must be signed in to change notification settings - Fork 0
/
24-thread.cc
79 lines (62 loc) · 1.74 KB
/
24-thread.cc
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
//
// Program
// This program utilizes std::shared_lock. Same as std::shared_mutex usage
// however makes use of std::shared_lock for lock management instead of
// directly calling std::shared_mutex interface.
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -pthread -o 24-thread 24-thread.cc
//
// Execution
// ./24-thread
//
#include <iostream>
#include <thread>
#include <shared_mutex>
using namespace std::chrono_literals;
//
// Function to be called for thread
//
static void thread_reader_func(std::shared_mutex& smutex) {
auto id = std::this_thread::get_id();
std::cout << __func__ << " is assigned to thread id # " << id << '\n';
std::this_thread::sleep_for(3s);
while (true) {
{
std::shared_lock<std::shared_mutex> lock(smutex);
std::cout << "Thread id # " << id << " rl" << '\n';
std::this_thread::sleep_for(4s);
}
std::cout << "Thread id # " << id << " rr" << '\n';
}
}
//
// Function to be called for thread
//
static void thread_writer_func(std::shared_mutex& smutex) {
auto id = std::this_thread::get_id();
std::cout << __func__ << " is assigned to thread id # " << id << '\n';
std::this_thread::sleep_for(1s);
while (true) {
{
std::shared_lock<std::shared_mutex> lock(smutex);
std::cout << "Thread id # " << id << " wl" << '\n';
std::this_thread::sleep_for(2s);
}
std::cout << "Thread id # " << id << " wr" << '\n';
}
}
//
// Entry function
//
int main() {
std::cout << "--- Shared lock ---" << '\n';
std::shared_mutex smutex;
std::thread t1(thread_reader_func, std::ref(smutex));
std::thread t2(thread_reader_func, std::ref(smutex));
std::thread t3(thread_writer_func, std::ref(smutex));
t1.join();
t2.join();
t3.join();
return 0;
}