-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9_Bankers_Algorithm.c
105 lines (90 loc) · 2.27 KB
/
9_Bankers_Algorithm.c
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
#include<stdio.h>
#define SIZE 50
void printMatrix(int Matrix[SIZE][SIZE], int n, int m){
int i, j;
for(i=0;i<n;i++){
printf(" ");
for(j=0;j<m;j++){
printf("%d ",Matrix[i][j]);
}
printf("\n");
}
}
int isArrayLess(int A[], int B[], int m){
int i;
for(i=0;i<m;i++){
if(A[i]>B[i]){
return 0;
}
}
return 1;
}
int main(){
int i, j, k, z, n, m, isSafe=1, Avail[SIZE], Work[SIZE], Finish[SIZE], safeSeq[SIZE], Max[SIZE][SIZE], Alloc[SIZE][SIZE], Need[SIZE][SIZE];
printf("Enter the No of Processes: ");
scanf(" %d",&n);
printf("Enter the No of type of Resources: ");
scanf(" %d",&m);
printf("Enter Available Resources: ");
for(i=0;i<m;i++){
scanf("%d",&Avail[i]);
Work[i]=Avail[i];
}
printf("Enter Maximum Resources required: \n");
for(i=0;i<n;i++){
printf(" p%d: ",i+1);
for(j=0;j<m;j++){
scanf(" %d",&Max[i][j]);
}
}
printf("Enter Resources allocated: \n");
for(i=0;i<n;i++){
printf(" p%d: ",i+1);
for(j=0;j<m;j++){
scanf(" %d",&Alloc[i][j]);
}
}
for(i=0;i<n;i++){
for(j=0;j<m;j++){
Need[i][j]=Max[i][j]-Alloc[i][j];
}
Finish[i]=0;
}
/*printf("\nAvailable Resources: ");
for(i=0;i<m;i++) {
printf("%d ", Avail[i]);
}
printf("\nMax Matrix:\n");
printMatrix(Max, n, m);
printf("\nAllocation Matrix:\n");
printMatrix(Alloc, n, m);*/
printf("\nNeed Matrix:\n");
printMatrix(Need, n, m);
z=0;
for(k=0;k<n;k++){
for(i=0;i<n;i++){
if(!Finish[i] && isArrayLess(Need[i], Work, m)){
Finish[i]=1;
safeSeq[z++]=i+1;
for(j=0;j<m;j++){
Work[j]+=Alloc[i][j];
}
}
}
}
for(i=0;i<n;i++){
if(!Finish[i]){
isSafe=0;
}
}
if(!isSafe)
printf("\nThe processes are not safe, will cause DeadLock.\n");
else{
printf("\nThe processes are safe.\nSafe Sequence: ");
printf("P%d ",safeSeq[0]);
for(i=1;i<n;i++)
printf("-> P%d ",safeSeq[i]);
printf("\n");
}
return 0;
}