EXPERIMENT NO – 7
a. Write a program to demonstrate the concept of deadlock avoidance through
Banker’s Algorithm
#include <stdio.h>
#include <stdbool.h>
#define P 5 // Number of processes
#define R 3 // Number of resources
int available[R] = {3, 3, 2}; // Available resources
int max_demand[P][R] = {
{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}
};
int allocation[P][R] = {
{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}
};
bool is_safe_state(int work[], int finish[], int safe_sequence[]) {
int count = 0;
bool allocated;
for (int i = 0; i < P; i++)
finish[i] = 0;
while (count < P) {
allocated = false;
for (int i = 0; i < P; i++) {
bool can_allocate = true;
for (int j = 0; j < R; j++) {
if (max_demand[i][j] - allocation[i][j] > work[j]) {
can_allocate = false;
break;
}
}
if (!finish[i] && can_allocate) {
for (int j = 0; j < R; j++)
work[j] += allocation[i][j];
safe_sequence[count++] = i;
finish[i] = 1;
allocated = true;
}
}
if (!allocated)
return false;
}
return true;
}
bool request_resources(int process_id, int request[]) {
for (int i = 0; i < R; i++) {
if (request[i] > max_demand[process_id][i] - allocation[process_id][i]) {
printf("Process %d has exceeded its maximum claim!\n", process_id);
return false;
}
if (request[i] > available[i]) {
printf("Resources not available for process %d request!\n", process_id);
return false;
}
}
for (int i = 0; i < R; i++) {
available[i] -= request[i];
allocation[process_id][i] += request[i];
}
int work[R], finish[P], safe_sequence[P];
for (int i = 0; i < R; i++)
work[i] = available[i];
if (is_safe_state(work, finish, safe_sequence)) {
printf("Request granted. Safe sequence: ");
for (int i = 0; i < P; i++)
printf("%d ", safe_sequence[i]);
printf("\n");
return true;
} else {
printf("Request denied. Would lead to an unsafe state.\n");
for (int i = 0; i < R; i++) {
available[i] += request[i];
allocation[process_id][i] -= request[i];
}
return false;
}
}
int main() {
int request[R] = {1, 0, 2};
int process_id = 1;
request_resources(process_id, request);
return 0;
}
OUTPUT:
Request granted.
Safe sequence: 1 3 4 0 2