-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive_mutex.cpp
More file actions
119 lines (50 loc) · 2 KB
/
Copy pathrecursive_mutex.cpp
File metadata and controls
119 lines (50 loc) · 2 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// TOPIC: Recursive Mutex In C++ (std::recursive_mutex)
// NOTES:
// 0. It is same as mutex but, Same thread can lock one mutex multiple times using recursive_mutex.
// 1. If thread T1 first call lock/try_lock on recursive mutex m1, then m1 is locked by T1, now
// as T1 is running in recursion T1 can call lock/try_lock any number of times there is no issue.
// 2. But if T1 have aquired 10 times lock/try_lock on mutex m1 then thread T1 will have to unlock
// it 10 times otherwise no other thread will be able to lock mutex m1.
// It means recursive_mutex keeps count how many times it was locked so that many times it should be unlocked.
// 3. How many time we can lock recursive_mutex is not defined but when that number reaches and if we were calling
// lock() it will return std::system_error OR if we were calling try_lock() then it will return false.
// BOTTOM LINE:
// 0. It is similar to mutex but have extra facitility that it can be locked multiple time by same thread.
// 1. If we can avoid recursive_mutex then we should becuase it brings overhead to the system.
// 2. It can be used in loops also.
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
// EXAMPLE 1: With Recursion
std::recursive_mutex m1;
int buffer = 0;
void recursion(char c, int loopFor) {
if(loopFor<0)
return;
m1.lock();
cout << "Locked By ThreadID:" << c << " " << buffer++ << endl;
recursion(c, --loopFor);
m1.unlock();
cout << "Unlocked By ThreadID:" << c << endl;
}
int main() {
thread t1(recursion, '1', 2);
thread t2(recursion, '2', 2);
t1.join();
t2.join();
return 0;
}
// EXAMPLE 2: With loop
// std::recursive_mutex m1;
// int main() {
// for(int i=0; i<5; i++) {
// m1.lock();
// std::cout << "locked " << i << endl;
// }
// for(int i=0; i<5; i++) {
// m1.unlock();
// std::cout << "ulocked " << i << endl;
// }
// return 0;
// }