// PROGRAM FOR THE IMPLEMENTATION OF THE BANKER'S ALGORITHM
//i.e to find safe or unsafe state
#include<stdio.h>
#define SIZE 20
int need[SIZE][SIZE],alloc[SIZE][SIZE],max[SIZE][SIZE];
int total[SIZE],avail[SIZE];
int main()
{
int n1,n2,i,j,flag,flag1,flag2,result;
int check[SIZE]={0};
printf("\n\tEnter the number of processes\t");
scanf("%d",&n1);
printf("\n\tEnter the number of resources\t");
scanf("%d",&n2);
for(i=0;i<n2;i++)
{
printf("\n\tEnter the maximum number of instances of resource R%d\t",i+1);
scanf("%d",&total[i]);
}
//input
for(i=0;i<n1;i++)
{
for(j=0;j<n2;j++)
{
printf("\n\tEnter maximum number of instances of resource R%d needed to process P%d\t ",j+1,i+1);
scanf("%d",&max[i][j]);
}
}
for(i=0;i<n1;i++)
{
for(j=0;j<n2;j++)
{
printf("\n\tEnter number of instances of resource R%dallocated to process P%d\t ",j+1,i+1);
scanf("%d",&alloc[i][j]);
}
}
// find number of process still needed
for(i=0;i<n1;i++)
{
for(j=0;j<n2;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
}
}
//Calculate no. of available resources
for(j=0;j<n2;j++)
{ avail[j]=0;
for(i=0;i<n1;i++)
{
avail[j]+=alloc[i][j];
}
avail[j]=total[j]-avail[j];
}
//compare the allocated and available resources
while(1)
{
flag1=1;
for(i=0;i<n1;i++)
{
for(j=0;j<n2;j++)
{
flag=1;
if(need[i][j]<avail[j])
{
flag=0;
}
else
{
flag=1;
break;
}
} //2nd for closed
if(flag==0 && check[i]==0)
{
flag1=0;
check[i]=1;
printf("\n\tProcess P%d executed",i+1);
for(j=0;j<n2;j++)
{
avail[j]=avail[j]+alloc[i][j];
}
break;
}
} //1st for closed
// whether all processes finsh to execute
for(i=0;i<n1;i++)
{
if(check[i]==0)
{
flag2=0;
break;
}
else //all process executed
flag2=1;
}
if(flag2==1)
{
result=0; //safe state
break;
}
if(flag1==1) //fail to alloc resources(unsafe)
{
result=1;
break;
}
}
if(result==0)
{
printf("\n\t SAFE STATE");
}
else
{
printf("\n\t UNSAFE STATE");
}
getch();
return 0;
}
Comments
Post a Comment