-
Notifications
You must be signed in to change notification settings - Fork 0
/
bankersAlgorithm.c
99 lines (97 loc) · 1.78 KB
/
bankersAlgorithm.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
#include<stdio.h>
#define true 1
#define false 0
int available[10], allocation[10][10], max[10][10], need[10][10], work[10], finish[10], maxres[10], safe[10], req[10], m, n;
int find()
{
int i, j;
for (i = 0; i < n; i++)
{
if (finish[i] == false)
{
for (j = 0; j < m; j++)
if (need[i][j] > work[j]) break;
if (j == m)
{
finish[i] = true;
return i;
}
}
}
return -1;
}
int is_safe()
{
int i = 0, j, k = 0, cnt = n;
for (j = 0; j < m; j++)
work[j] = available[j];
for (j = 0; j < m; j++)
finish[i] = false;
while (cnt > 0)
{
for (i = 0; i < n; i++)
{
i = find();
if (i == -1)
{
printf("\nThe system is in unsafe state\n");
return 0;
}
for (j = 0; j < m; j++)
work[j] += allocation[i][j];
safe[k++] = i;
cnt--;
}
}
if (finish[i - 1] == false)
{
printf("\nThe system is in unsafe state\n");
return 0;
}
printf("\nThe system is in safe state\n");
return 0;
}
int main()
{
int i, j, sum;
char ch;
printf("\nEnter the number of processes and the number of resources: ");
scanf("%d%d", &n, &m);
printf("\nEnter maximum instances of resources\n");
for (j = 0; j < m; j++)
{
scanf("%d", &maxres[j]);
available[j] = maxres[j];
}
printf("\nEnter the Allocated Matrix:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
scanf("%d", &allocation[i][j]);
}
printf("\nEnter the Max Matrix:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
scanf("%d", &max[i][j]);
need[i][j] = max[i][j] - allocation[i][j];
}
}
printf("\nThe Need Matrix is:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
printf("%d ", need[i][j]);
printf("\n");
}
for (j = 0; j < m; j++)
{
sum = 0;
for (i = 0; i < n; i++)
sum += allocation[i][j];
available[j] -= sum;
}
is_safe();
return 0;
}