Problem
No: 12
Name
of the problem: Banker’s algorithm
Theory:
The banker’s algorithm is a resource allocation and deadlock
avoidance algorithm that tests for safety by simulating the allocation for
predetermined maximum possible amounts of all resources then make an
“s-state” check to test for possible activities, before deciding whether
allocation should be allowed to continue.
Code:
#include<bits/stdc++.h>
using
namespace std;
#include<string.h>
int main()
{
int
n,m,i,j,k,f=0,ar[10],z=0;//n=no_of_process,m=no_of_resources
printf("Enter the number of
processes -");
scanf("%d",&n);
int finished[n];
memset(finished+0,0,n*sizeof(int));
printf("Enter the number of
resources -");
scanf("%d",&m);
int
allocation[n][m],need[n][m],max[n][m],available[m],request[m];
for(i=0; i<n; i++)
{ printf("Enter details for P%d\nEnter
allocation\t\t-",i);
for(j=0; j<m; j++)
{scanf("%d",&allocation[i][j]);
}
printf("Enter max\t\t\t-");
for(j=0; j<m; j++)
{
scanf("%d",&max[i][j]);
need[i][j]=max[i][j]-allocation[i][j];
}
}
printf("Enter Available
Resources\t-");
for(i=0; i<m; i++)
scanf("%d",&available[i]);
printf("Enter new request
details--\nEnter pid\t\t\t");
int temp;
scanf("%d",&temp);
printf("Enter new request
details\t-");
for(i=0; i<m; i++)
{scanf("%d",&request[i]);
available[i]=available[i]-request[i];
allocation[temp][i]=
allocation[temp][i]+request[i];
need[temp][i]=max[temp][i]-allocation[temp][i];
cout<<"----------------OUTPUT-----------------"<<endl<<endl;
int loop=n;
while(loop--)
{for(i=0; i<n; i++)
{if(finished[i]==0)
{
k=0;
for(j=0; j<m; j++)
{
if(need[i][j]<=available[j])
k++;
else
break;
}
if(k==m)
{
finished[i]=1;
f++;
printf("\nP%d is
visited ",i);
ar[z++]=i;
for(j=0; j<m; j++)
{
available[j]=allocation[i][j]+available[j];
printf("%d
",available[j]);
}}}}
if(f==n)
{break; }
}
cout<<"System in safe
state"<<endl<<"Safe sequence--( ";
for(i=0; i<z; i++)
{
cout<<"P"<<ar[i]<<" ";
}
cout<<" )";
printf("\n");
for(i=0; i<n; i++)
{
printf("\nP%d\t",i);
for(k=0; k<m; k++)
printf("%d
",allocation[i][k]);
printf("\t");
for(k=0; k<m; k++)
printf("%d ",max[i][k]);
printf("\t");
for(k=0; k<m; k++)
printf("%d ",need[i][k]);
}}
No comments:
Post a Comment