0% found this document useful (0 votes)
5 views

bankers algorithm

The document contains a C program that implements the Banker's Algorithm for deadlock avoidance in operating systems. It prompts the user to input the number of processes, resources, allocation matrix, maximum matrix, and available resources, then calculates the need matrix and determines if the system is in a safe state. If safe, it outputs the safe sequence of processes; otherwise, it indicates a potential deadlock.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

bankers algorithm

The document contains a C program that implements the Banker's Algorithm for deadlock avoidance in operating systems. It prompts the user to input the number of processes, resources, allocation matrix, maximum matrix, and available resources, then calculates the need matrix and determines if the system is in a safe state. If safe, it outputs the safe sequence of processes; otherwise, it indicates a potential deadlock.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <conio.h>

#define MAX 10

int main() {
int alloc[MAX][MAX], max[MAX][MAX], need[MAX][MAX];
int avail[MAX], completed[MAX], safeSeq[MAX];
int p, r, i, j, process, count = 0;
int flag;

clrscr();

printf("Enter the number of processes: ");


scanf("%d", &p);

printf("Enter the number of resources: ");


scanf("%d", &r);

printf("\nEnter Allocation Matrix:\n");


for (i = 0; i < p; i++) {
for (j = 0; j < r; j++) {
scanf("%d", &alloc[i][j]);
}
}

printf("\nEnter Maximum Matrix:\n");


for (i = 0; i < p; i++) {
for (j = 0; j < r; j++) {
scanf("%d", &max[i][j]);
}
}

printf("\nEnter Available Resources:\n");


for (i = 0; i < r; i++) {
scanf("%d", &avail[i]);
}

// Calculate Need Matrix


for (i = 0; i < p; i++) {
for (j = 0; j < r; j++) {
need[i][j] = max[i][j] - alloc[i][j];
}
completed[i] = 0;
}

// Banker's Algorithm
while (count < p) {
flag = 0;
for (i = 0; i < p; i++) {
if (!completed[i]) {
int canAllocate = 1;
for (j = 0; j < r; j++) {
if (need[i][j] > avail[j]) {
canAllocate = 0;
break;
}
}
if (canAllocate) {
for (j = 0; j < r; j++) {
avail[j] += alloc[i][j];
}
safeSeq[count++] = i;
completed[i] = 1;
flag = 1;
}
}
}
if (!flag) {
break;
}
}

// Result
if (count == p) {
printf("\nSystem is in a safe state.\nSafe sequence is: ");
for (i = 0; i < p; i++) {
printf("P%d ", safeSeq[i]);
}
} else {
printf("\nSystem is not in a safe state. Deadlock may occur.");
}

getch();
return 0;
}

You might also like