操作系统用C++语言写银行家算法给出代码
时间: 2023-03-11 07:42:23 浏览: 124
操作系统用C语言写银行家算法的代码如下: #include<stdio.h>
#define n 5
int main()
{
int need[n],allocate[n],max[n],avail[n],safeseq[n];
int i,j,exec,r,p,count;
count=0;
printf("\nEnter the number of processes :");
scanf("%d",&p);
printf("\n Enter the number of resources :");
scanf("%d",&r);
printf("\n Enter the Maximum Matrix for each process : ");
for(i=0;i<p;i++)
{
printf("\n For process %d : ",i+1);
for(j=0;j<r;j++)
scanf("%d",&max[i][j]);
}
printf("\n Enter the allocation for each process : ");
for(i=0;i<p;i++)
{
printf("\n For process %d : ",i+1);
for(j=0;j<r;j++)
scanf("%d",&allocate[i][j]);
}
printf("\nEnter the Available Resources : ");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
for(i=0;i<p;i++)
for(j=0;j<r;j++)
need[i][j]=max[i][j]-allocate[i][j];
do
{
printf("\n Max matrix:\tAllocation matrix:\n");
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
printf("%d\t",max[i][j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d\t",allocate[i][j]);
printf("\n");
}
exec=-1;
for(i=0;i<p;i++)
{
if(exec==-1)
{
for(j=0;j<r;j++)
{
if(need[i][j]>avail[j])
break;
}
if(j==r)
exec=i;
}
}
if(exec!=-1)
{
printf("\nProcess %d is executing\n",exec+1);
safeseq[count]=exec+1;
count++;
for(j=0;j<r;j++)
avail[j]+=allocate[exec][j];
need[exec][j]=0;
for(i=0;i<r;i++)
{
if(i==r)
break;
else
need[exec][i]=0;
}
}
}while(count!=p&&exec!=-1);
if(count==p)
{
printf("\nThe system is in a safe state.\n");
printf("Safe Sequence : < ");
for(i=0;i<p;i++)
printf("%d ",safeseq[i]);
printf(">\n");
}
else
printf("\nThe system is in an unsafe state.");
return 0;
}
阅读全文