Bankers Algorithm Program
Bankers Algorithm Program
h>
//global variables.
int Pcurr[3][3]; //max of 3 processes, 3 resources
int Pmax[3][3];
int avl[]={6,4,7};
int avltemp[]={6,4,7};
int maxres[]={6,4,7};
main()
for(i=0;i<3;i++)
running[i]=1; //set all the processes to "running" = true (1)
int ch;
initresources();
system("clear"); //calls a command prompt command, this looks like unix clear
screen to manage the output.
scanf("%d",&ch);
if(ch==1)
{
requestresource();
getchar();
}
else if(ch==2)
{
viewresources();
getchar();
}
else if(ch==3)
break;
else
printf("\nInvalid Choice, please try again!\n");
}
}
//for each process, get curr. requirement and max. requirement->check if max.
req....
Pmax[0][0]=3; Pcurr[0][0]=1; avl[0]=3;
Pmax[0][1]=3; Pcurr[0][1]=2; avl[1]=1;
Pmax[0][2]=2; Pcurr[0][2]=2; avl[2]=1;
Pmax[1][0]=1; Pcurr[1][0]=1;
Pmax[1][1]=2; Pcurr[1][1]=0;
Pmax[1][2]=3; Pcurr[1][2]=3;
Pmax[2][0]=1; Pcurr[2][0]=1;
Pmax[2][1]=1; Pcurr[2][1]=1;
Pmax[2][2]=5; Pcurr[2][2]=1;
}
}
getchar();
if(allocate(proc,res))
{
printf("\nResources successfully allocated.\n");
if(checkcompletion(proc))
printf("\nProcess %d has completed its execution and its resources have been
released.\n",proc+1);
}
else
printf("\nResouces cannot be allocated as it may lead to Deadlock!\n");
}
else
{
printf("\nInvalid Process no.\n");
getchar();
}
}
// this is what you want: the bankers algorithm portion of the code! It uses the
algorithm to generate a true or false (safe or unsafe) value
//which is used to see if a resource can be allocated to a given process.
int checksafe()
{
//Check if atleast one process can get all resources it needs --> Banker's
algorithm
safe=0;
for(i=0;i<3;i++)
{
avltemp[i]=avl[i];
}
for(i=0;i<3;i++)
{
if(running[i])
{
if((Pmax[i][0]-Pcurr[i][0]<=avltemp[0])&&(Pmax[i][1]-
Pcurr[i][1]<=avltemp[1])&&(Pmax[i][2]-Pcurr[i][2]<=avltemp[2]))
{
for(j=0;j<3;j++)
avltemp[j]+=Pcurr[i][j];
safe=1;
}
}
}
return safe;
}