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