-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeadlock_prevention.cpp
More file actions
49 lines (41 loc) · 1.14 KB
/
deadlock_prevention.cpp
File metadata and controls
49 lines (41 loc) · 1.14 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
#include<iostream>
#include<thread>
#include<mutex>
#include<chrono>
using namespace std;
mutex mtxA;
mutex mtxB;
void safe_lock1(){
cout<< "Accessing resource A - thread 1 "<<endl;
mtxA.lock();
cout<< "Acquired resource A- thread 1"<<endl;
this_thread::sleep_for(chrono::seconds(1));
cout<< "Accessing resource B - thread 1 "<<endl;
mtxB.lock();
cout<< "Acquired resource B- thread 1"<<endl;
this_thread::sleep_for(chrono::seconds(1));
mtxB.unlock();
cout<<"Released resource B"<<endl;
mtxA.unlock();
cout<<"Released resource A"<<endl;
}
void safe_lock2(){
cout<< "Accessing resource A - thread 2 "<<endl;
mtxA.lock();
cout<< "Acquired resource A- thread 2"<<endl;
this_thread::sleep_for(chrono::seconds(1));
cout<< "Accessing resource B - thread 2 "<<endl;
mtxB.lock();
cout<< "Acquired resource B- thread 2"<<endl;
this_thread::sleep_for(chrono::seconds(1));
mtxB.unlock();
cout<<"Released resource B"<<endl;
mtxA.unlock();
cout<<"Released resource A"<<endl;
}
int main(){
thread t1(safe_lock1);
thread t2(safe_lock2);
t1.join();
t2.join();
}