-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeadlock_avoidance.cpp
More file actions
91 lines (75 loc) · 1.84 KB
/
deadlock_avoidance.cpp
File metadata and controls
91 lines (75 loc) · 1.84 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
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int>resources={10,5,7};
vector<vector<int>>max={
{7,5,3},
{3,2,2},
{9,0,2},
{2,2,2},
{4,3,3}
};
vector<vector<int>>allocated={
{0,1,0},
{2,0,0},
{3,0,2},
{2,1,1},
{0,0,2}
};
int n=5; //number of processes
int m=3; //number of resources
vector<vector<int>>need(n, vector<int>(m));
for(int i=0;i<n;i++){
for(int j=0; j<m;j++){
need[i][j]=max[i][j]-allocated[i][j];
}
}
vector<int>available(m);
for(int i=0;i<m;i++){
int sum=0;
for(int j=0;j<n;j++){
sum+=allocated[j][i];
}
available[i]=resources[i]-sum ;
}
vector<bool>finished(n,false);
vector<int>safeSeq;
int count=0;
while(count<n){
bool found = false;
for(int i=0;i<n;i++){
if(!finished[i]){
bool canRun= true;
for(int j=0;j<m;j++){
if(need[i][j]>available[j]){
canRun=false;
break;
}
}
if(canRun){
for(int j=0;j<m;j++){
available[j]+=allocated[i][j];
}
safeSeq.push_back(i);
found=true;
finished[i]=true;
count++;
}
}
}
if(!found){
break;
}
}
if(count==n){
cout<<"System is safe\nSafe sequence is"<<endl;
for(int i:safeSeq){
cout<<"P"<<i<<" ";
}
cout<<endl;
}
else{
cout<<"System is not safe"<<endl;
}
}