一、要求
模拟实现银行家算法,用银行家算法实现资源分配和安全性检查
进程可动态的申请和释放资源,系统按各进程的申请动态地分配资源
二、程序数据结构介绍
m:资源的类型 n:进程的数量 Requesti:进程Pi的请求向量 ava:一个长度为m向量,表示每类资源的可用数目 all:一个m×n矩阵,定义当前分配给每个进程每类资源的数目 nd:一个m×n矩阵,表示每个进程还需多少资源 max:一个m×n矩阵,定义每个进程的最大资源需求数
三、代码
#include<stdio.h>
#include <stdlib.h>
int n;
int m;
int request[100];
int ava[100];
int all[100][100];
int nd[100][100];
int max[100][100];
void menu()
{
printf("1、judge the system security\n");
printf("2、judge the request security\n");
printf("3、创建新的进程\n");
printf("0、quit\n");
}
int safe()
{
int finish[n],work[n][m],w[m],a[n],flag;
int i,j,k,c,s,b,p;
c=0;
b=0;
flag=0;
for(i=0;i<m;i++)
w[i]=ava[i];
for(i=0;i<n;i++)
{finish[i]=0;}
for(i=0;flag<n;i=(i+1)%n)
{
p=1;
for(j=0;j<m;j++)
if(finish[i]!=0||nd[i][j]>w[j])
p=0;
if(p)
{
for(j=0;j<m;j++)
{
work[i][j]=w[j]+all[i][j];
w[j]+=all[i][j];
}
finish[i]=1;
a[c]=i;
c++;
flag=0;
}
else
{
flag++;}
}
flag=0;
for(k=0;k<n;k++)
{if(finish[k]==1)
flag++;}
if(flag==n)
{
printf("Name\tWork\tNeed\tAllocation\tWork+ Allocation\tFinish\n");
for(c=0;c<n;c++)
{
printf("p%d\t",a[c]);
for(i=0;i<m;i++)
printf("%d ",work[a[c]][i]-all[a[c]][i]);
printf("\t");
for(i=0;i<m;i++)
printf("%d ",nd[a[c]][i]);
printf("\t ");
for(i=0;i<m;i++)
printf("%d ",all[a[c]][i]);
printf("\t\t");
for(i=0;i<m;i++)
printf("%d ",work[a[c]][i]);
printf("\t\t\tT\n");
}
return 1;
}
else
return 0;
}
void accepetRequest()
{
int i,j,na,p;
printf("Please input the customer’s name and request\np");
scanf("%d",&na);
if(na>n-1)
{printf("CUSTOMER p%d IS NOT EXIST!!",na);exit(0);}
else
p=1;
for(i=0;i<m;i++)
{scanf("%d",&request[i]);
for(j=0;j<m;j++)
{
if(request[j]>nd[na][j])
p=0;
if(request[j]>ava[j])
p=2;
}}
if(p==1)
{
for(i=0;i<m;i++)
{
ava[i]-=request[i];
all[na][i]+=request[i];
nd[na][i]-=request[i];
}
safe();
printf("SYSTEM SECURITY!!!\nCUSTOMER p%d CAN GET RESOURCES IMMEDIATELY!!!\n",na);
}
else if(p==0)
printf("RESOURCE INSECURITY!!!\nCUSTOMER p%d CAN NOT OBTAIN RESOURCES IMMEDIATELY!!!\n",na);
else
printf("SYSTEM INSUFFICIENT!!!!!!\nCUSTOMER p%d CAN NOT OBTAIN RESOURCES IMMEDIATELY!!!\n",na);
}
void creat1()
{
int i,j;
printf("Input the amount of resource (maximum , allocated) of each customer:(数字之间用空格隔开)\n");
for(i=0;i<n;i++)
{
printf("p%d\t",i);
for(j=0;j<m;j++)
scanf("%d",&max[i][j]);
for(j=0;j<m;j++)
{
scanf("%d",&all[i][j]);
nd[i][j]=max[i][j]-all[i][j];
}
}
printf("Input the amout of resources(available):\n");
for(i=0;i<m;i++)
scanf("%d",&ava[i]);
}
int main()
{
int x;
char choose;
printf("Input the type of resource and number of customer:\n");
scanf("%d%d",&m,&n);
creat1();
while(1)
{
menu();
choose=getch();
switch(choose)
{
case '1': x=safe();
if(x==0)
printf("SYSTEM INSUFFICIENT!!!\n");
else
printf("SYSTEM SECURITY!!!\n");break;
case '2':accepetRequest(); break;
case '3':printf("Input the type of resource and number of customer:\n");
scanf("%d%d",&m,&n);
creat1();break;
case '0':exit(0);
default:printf("错误的数字,请重新输入\n");
}
}
return 0;
}