-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9_Detect_DeadLock.c
More file actions
106 lines (92 loc) · 2.67 KB
/
9_Detect_DeadLock.c
File metadata and controls
106 lines (92 loc) · 2.67 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
Enter the number of processes: 3
Enter the number of resources: 3
Enter allocation matrix:
0 1 0
1 1 0
0 0 1
Enter maximum demand matrix:
1 0 0
0 0 1
0 1 0
Enter available resources vector:
0 0 0
System is in deadlock.
Enter the number of processes: 3
Enter the number of resources: 3
Enter allocation matrix:
0 1 0
1 1 0
0 0 1
Enter maximum demand matrix:
1 0 0
0 0 1
0 0 0
Enter available resources vector:
0 0 0
System is in a safe state. Safe sequence: 2 1 0
*/
#include <stdio.h>
#include <stdbool.h>
#define MAX_PROCESSES 100
#define MAX_RESOURCES 100
int main() {
int processes, resources, i, j ,allocation[MAX_PROCESSES][MAX_RESOURCES];
int max_demand[MAX_PROCESSES][MAX_RESOURCES] ,available[MAX_RESOURCES],work[MAX_RESOURCES];
bool finished[MAX_PROCESSES],safe_state = true;
printf("Enter the number of processes: ");
scanf("%d", &processes);
printf("Enter the number of resources: ");
scanf("%d", &resources);
printf("Enter allocation matrix:\n");
for (i = 0; i < processes; i++) {
for (j = 0; j < resources; j++) scanf("%d", &allocation[i][j]);
}
printf("Enter maximum demand matrix:\n");
for (i = 0; i < processes; i++) {
for (j = 0; j < resources; j++) scanf("%d", &max_demand[i][j]);
}
printf("Enter available resources vector:\n");
for (j = 0; j < resources; j++) scanf("%d", &available[j]);
for (i = 0; i < processes; i++) finished[i] = false;
for (j = 0; j < resources; j++) work[j] = available[j];
int safe_sequence[MAX_PROCESSES];
int count = 0;
while (count < processes) {
bool found = false;
for (i = 0; i < processes; i++) {
if (!finished[i]) {
bool can_allocate = true;
for (j = 0; j < resources; j++) {
if (max_demand[i][j] - allocation[i][j] > work[j]) {
can_allocate = false;
break;
}
}
if (can_allocate) {
for (j = 0; j < resources; j++) {
work[j] += allocation[i][j];
}
finished[i] = true;
safe_sequence[count] = i;
count++;
found = true;
}
}
}
if (!found) {
safe_state = false;
break;
}
}
if (safe_state) {
printf("System is in a safe state. Safe sequence: ");
for (i = 0; i < processes; i++) {
printf("%d ", safe_sequence[i]);
}
printf("\n");
} else {
printf("System is in deadlock.\n");
}
return 0;
}