-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_recursion_lock.cpp
More file actions
54 lines (45 loc) · 1.09 KB
/
06_recursion_lock.cpp
File metadata and controls
54 lines (45 loc) · 1.09 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
#include <bits/stdc++.h>
#include <mutex>
#include <thread>
using namespace std;
// Recursive mutex
recursive_mutex recursive_mut, loop_mut;
int criticalVariable = 0;
void recursion(const char *desc, int loop)
{
if (loop < 0)
return;
// Critical Section begins
recursive_mut.lock();
cout << desc << " | Value: " << criticalVariable++ << "\n";
recursion(desc, loop - 1);
// NOTE: Unlock should be called as many times as lock was done, otherwise no other thread will be able to access that lock
recursive_mut.unlock();
cout << "Unlocked by " << desc << "\n";
// Critical Section ends
}
void loop()
{
for (int i = 0; i < 5; i++)
{
loop_mut.lock();
cout << "Locked " << i << "\n";
}
for (int i = 0; i < 5; i++)
{
loop_mut.unlock();
cout << "Unlocked " << i << "\n";
}
}
int main()
{
int counter = 10;
thread t1(recursion, "Thread 1 ", counter);
thread t2(recursion, "Thread 2 ", counter);
if (t1.joinable())
t1.join();
if (t2.joinable())
t2.join();
loop();
return 0;
}