-
Notifications
You must be signed in to change notification settings - Fork 0
/
21-thread.cc
76 lines (65 loc) · 1.73 KB
/
21-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
//
// Program
// This program simply creates a recursive mutex.
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -pthread -o 21-thread 21-thread.cc
//
// Execution
// ./21-thread
//
#include <iostream>
#include <thread>
#include <mutex>
using namespace std::chrono_literals;
//
// Function to be called to access shared resource
//
static void shared_resource(std::recursive_mutex& rmutex, std::thread::id thread_id, int repeat)
{
try {
for (int i = 0; i < repeat; ++i) {
rmutex.lock();
std::cout << "# " << i << ": shared_resource is used by thread # " << thread_id << '\n';
rmutex.unlock();
}
} catch(const std::system_error& e) {
std::cout << "Caught system_error" << '\n'
<< " - error code: " << e.code() << '\n'
<< " - message: " << e.what() << '\n';
}
}
//
// Function to be called for thread
//
static void thread_callback_1(std::recursive_mutex& rmutex) {
auto id = std::this_thread::get_id();
std::cout << __func__ << " is assigned to thread id # " << id << '\n';
for (int i=1; i < 5; ++i) {
shared_resource(rmutex, id, i);
std::this_thread::sleep_for(2s);
}
}
//
// Function to be called for thread
//
static void thread_callback_2(std::recursive_mutex& rmutex) {
auto id = std::this_thread::get_id();
std::cout << __func__ << " is assigned to thread id # " << id << '\n';
for (int i=1; i < 6; ++i) {
shared_resource(rmutex, id, i);
std::this_thread::sleep_for(3s);
}
}
//
// Entry function
//
int main() {
std::cout << "--- Recursive mutex ---" << '\n';
std::recursive_mutex rmutex;
std::thread t1(thread_callback_1, std::ref(rmutex));
std::thread t2(thread_callback_2, std::ref(rmutex));
t1.join();
t2.join();
return 0;
}