Bankers algorithm

/**/
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>

int main(){
int i,j,k=0,count=0,n,remain,r,temp;
printf("Enter number of resources : ");
scanf("%d",&r);
printf("Enter number of processes : ");
scanf("%d",&n);
remain=n;
int tot_res_ins[r],available[r],ins_alloc[r],allocated[n][r],max[n][r],need[n][r],ss[n];
bool finish[n];
printf("Enter total instances of each resource : ");
for(i=0;i<r;i++){
scanf("%d",&tot_res_ins[i]);
ins_alloc[i]=0;
}
printf("Enter allocated matrix : \n");
for(i=0;i<n;i++){
finish[i]=false;
for(j=0;j<r;j++){
scanf("%d",&allocated[i][j]);
ins_alloc[j]+=allocated[i][j];
}
}
printf("Enter max matrix : \n");
for(i=0;i<n;i++){
for(j=0;j<r;j++){
scanf("%d",&max[i][j]);
need[i][j]=max[i][j]-allocated[i][j];
}
}
for(j=0;j<r;j++) available[j]=tot_res_ins[j]-ins_alloc[j];


for(i=0;i<n;i++){
temp=0;
if(!finish[i]){
for(j=0;j<r && need[i][j] <= available[j];j++) temp++;
if(temp==r){
finish[i]=1;
for(j=0;j<r;j++) available[j]+=allocated[i][j];
ss[k++]=i+1;
remain--;
count=0;

printf("P[%d]\t",i+1);
for(j=0;j<r;j++) printf("%2d",allocated[i][j]);
printf("\t");
for(j=0;j<r;j++) printf("%2d",max[i][j]);
printf("\t");
for(j=0;j<r;j++) printf("%2d",need[i][j]);
printf("\t");
for(j=0;j<r;j++) printf("%2d",available[j]);
printf("\ttrue\n");
}
else count++;
}
if(remain==0){
printf("\n\nSafe Sequence:-\n");
for(j=0;j<n;j++) printf("%d\t",ss[j]);
printf("\n");
exit(1);
}
if(count==remain){
printf("System is in Deadlock\n The Deadlock Processes are : \n");
for(j=0;j<n;j++) printf("P[%d]\t",j+1);
printf("\n");
exit(1);
}
if(i==n-1) i=-1;
}
}


Output :



Comments

Popular Posts