0% found this document useful (0 votes)
12 views4 pages

Lab 9

Uploaded by

Maaz Sayyed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views4 pages

Lab 9

Uploaded by

Maaz Sayyed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Experiment Number: 9

NAME: Sayyed Md Muaz Aslam ROLLNO: 60


CLASS: TY_IT_A BATCH: B3
PRN No.: 12110133

Problem Statement:

Q) : Write a program to check whether given system is in safe state or not using
Banker’s Deadlock Avoidance algorithm.

Problem:

#include <stdio.h>

int main() {
int n, m; // Number of processes and
resources printf("Enter the number of
processes: "); scanf("%d", &n);
printf("Enter the number of resources: ");
scanf("%d", &m);

int max[n] // Maximum resource allocation for each


[m];allocation[n][m];
int process
// Current resource allocation for each
process int need[n][m];// Resource need for each process
int available[m];// Available resources

// Input maximum resource allocation for each process


printf("Enter the maximum resource allocation for each
process:\n"); for (int i = 0; i < n; i++) {
printf("Process %d: ", i + 1); for (int j = 0; j < m; j++) {
scanf("%d", &max[i][j]);
}
}

// Input current resource allocation for each process


printf("Enter the current resource allocation for each
process:\n"); for (int i = 0; i < n; i++) {
printf("Process %d: ", i + 1); for (int j = 0; j < m; j++) {
scanf("%d", &allocation[i][j]);
need[i][j] = max[i][j] - allocation[i][j];
}
}

// Input available resources printf("Enter the available


resources: "); for (int i = 0; i < m; i++) {
scanf("%d", &available[i]);
}
// Initialize a boolean array to track the state of
processes int finish[n];
for (int i = 0; i < n;
i++) { finish[i] =
0;
}

int
safe_sequence[n];
int count = 0;
int safe = 1; // Assume the system is initially in a safe state

while (count < n) {


safe = 0; // Assume the system is not in a safe state

for (int i = 0; i < n;


i++) { if (finish[i]
== 0) {
int can_allocate = 1;

for (int j = 0; j < m; j++) {


if (need[i][j] >
available[j]) {
can_allocate = 0;
break;
}
}

if (can_allocate) {
for (int j = 0; j < m; j++) {
available[j] +=
allocation[i][j];
}

safe_sequence[count]
= i; finish[i] = 1;
count++;
safe = 1; // The system is in a safe state after allocation
}
}
}

if (!safe)
{ bre
ak;
}
}

if (safe) {
printf("The system is in a safe
state.\n"); printf("Safe Sequence:
");
for (int i = 0; i < n; i++) {
printf("P%d",
safe_sequence[i]); if (i < n -
1) {
printf(" -> ");
}
}
printf("\n");
} else {
printf("The system is not in a safe state. Deadlock detected.\n");
}

return 0;
}
Output:

You might also like