-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWrite a program to implement the banker_s algorithm.c
79 lines (69 loc) · 1.87 KB
/
Write a program to implement the banker_s 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
#include <stdio.h>
#include <stdbool.h>
#define MAX_PROCESSES 5
#define MAX_RESOURCES 3
int main() {
int n, m, i, j, k;
n = MAX_PROCESSES; // Number of processes
m = MAX_RESOURCES; // Number of resources
int allocation[MAX_PROCESSES][MAX_RESOURCES] = {
{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}
};
int max[MAX_PROCESSES][MAX_RESOURCES] = {
{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}
};
int available[MAX_RESOURCES] = {3, 3, 2};
int need[MAX_PROCESSES][MAX_RESOURCES];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
bool finish[MAX_PROCESSES] = {0};
int safeSequence[MAX_PROCESSES];
int work[MAX_RESOURCES];
for (i = 0; i < m; i++) {
work[i] = available[i];
}
int count = 0;
while (count < n) {
bool found = false;
for (i = 0; i < n; i++) {
if (!finish[i]) {
bool possible = true;
for (j = 0; j < m; j++) {
if (need[i][j] > work[j]) {
possible = false;
break;
}
}
if (possible) {
for (k = 0; k < m; k++) {
work[k] += allocation[i][k];
}
safeSequence[count++] = i;
finish[i] = true;
found = true;
}
}
}
if (!found) {
printf("The system is not in a safe state.\n");
return -1;
}
}
printf("The system is in a safe state.\nSafe sequence is: ");
for (i = 0; i < n; i++) {
printf("%d ", safeSequence[i]);
}
printf("\n");
return 0;
}