Banker's Algorithm Implementation in C
This program demonstrates the Banker's Algorithm, a classic deadlock avoidance strategy used in operating systems to manage resource allocation safely.
C Source Code
#include <stdio.h>
int n, m;
int alloc[10][10], max[10][10], need[10][10];
int avail[10], work[10], finish[10];
// Safety Algorithm
int checkSafety() {
int seq[10], count = 0;
for (int i = 0; i < n; i++) finish[i] = 0;
for (int i = 0; i < m; i++) work[i] = avail[i];
while (count < n) {
int found = 0;
for (int i = 0; i < n; i++) {
if (!finish[i]) {
int j;
for (j = 0; j < m; j++) {
if (need[i][j] > work[j]) break;
}
if (j == m) {
for (int k = 0; k < m; k++) work[k] += alloc[i][k];
seq[count++] = i;
finish[i] = 1;
found = 1;
}
}
}
if (!found) break;
}
if (count == n) {
printf("\nSystem is SAFE\nSafe Sequence: ");
for (int i = 0; i < n; i++) printf("P%d ", seq[i]);
printf("\n");
return 1;
} else {
printf("\nSystem is UNSAFE\n");
return 0;
}
}
int main() {
int p, req[10];
printf("Enter number of processes and resources: ");
scanf("%d %d", &n, &m);
printf("\nEnter Allocation Matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) scanf("%d", &alloc[i][j]);
printf("\nEnter Max Matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
scanf("%d", &max[i][j]);
need[i][j] = max[i][j] - alloc[i][j];
}
printf("\nEnter Available Resources:\n");
for (int i = 0; i < m; i++) scanf("%d", &avail[i]);
// Initial Safety Check
checkSafety();
// Request Section
printf("\nEnter process number (0 to %d): ", n - 1);
scanf("%d", &p);
printf("Enter request for that process:\n");
for (int i = 0; i < m; i++) scanf("%d", &req[i]);
// Check request <= need
for (int i = 0; i < m; i++) {
if (req[i] > need[p][i]) {
printf("\nRequest exceeds need → DENIED\n");
return 0;
}
}
// Check request <= available
for (int i = 0; i < m; i++) {
if (req[i] > avail[i]) {
printf("\nResources not available → WAIT\n");
return 0;
}
}
// Pretend allocation
for (int i = 0; i < m; i++) {
avail[i] -= req[i];
alloc[p][i] += req[i];
need[p][i] -= req[i];
}
printf("\nChecking system after allocation...\n");
// Final safety check
if (checkSafety()) {
printf("Request GRANTED\n");
} else {
printf("Request leads to UNSAFE state → ROLLING BACK\n");
// Rollback
for (int i = 0; i < m; i++) {
avail[i] += req[i];
alloc[p][i] -= req[i];
need[p][i] += req[i];
}
}
return 0;
}How the Algorithm Works
- Safety Check: Determines if the system can satisfy all requests without entering a deadlock.
- Resource Request: Validates if the requested resources are within the process's declared maximum needs.
- Rollback Mechanism: If a request leads to an unsafe state, the system reverts the allocation to maintain stability.
English with a size of 3.52 KB