#include <stdio.h>
#include <string.h>
#define size 50
typedef struct bank
{
int process;//进程数
int resource;//资源数
int Max[size][size];//最大需求量
int Allcation[size][size];//已分配资源数
int Need[size][size];//还需资源数
int Available[size];
}Bank;
Bank bank;
int k = 0;
int vis[size]; //标记数组
int SafeSeq[size];
void ScanfResource()
{
int i,j;
for(i = 0;i < bank.process;i ++)
{
printf("----------第%d进程----------\n",i + 1);
printf("最大资源量:",i + 1);
for(j = 0;j < bank.resource;j ++)
{
scanf("%d",&bank.Max[i][j]);
}
printf("\n");
printf("已分配资源量:",i + 1);
for(j = 0;j < bank.resource;j ++)
{
scanf("%d",&bank.Allcation[i][j]);
}
for(j = 0;j < bank.resource;j ++)
{
bank.Need[i][j] = bank.Max[i][j] - bank.Allcation[i][j];
}
if(i == bank.process - 1 )
printf("--------------------------------\n");
}
}
void PrintfInfo()
{
int i,j;
printf("进程\t最大资源量\t已分配资源量\t还需资源量\n");
for(i = 0;i < bank.process;i ++)
{
printf("%d\t",i + 1);
for(j = 0;j < bank.resource;j ++)
{
if(j == bank.resource - 1)
printf("%d \t",bank.Max[i][j]);
else
printf("%d ",bank.Max[i][j]);
}
for(j = 0;j < bank.resource;j ++)
{
if(j == bank.resource - 1)
printf("%d \t",bank.Allcation[i][j]);
else
printf("%d ",bank.Allcation[i][j]);
}
for(j = 0;j < bank.resource;j ++)
{
if(j == bank.resource - 1)
printf("%d",bank.Need[i][j]);
else
printf("%d ",bank.Need[i][j]);
}
printf("\n");
}
}
void InitResource()
{
int i,j;
int s;
printf("请输入每种资源的数量:\n");
for(i = 0;i < bank.resource;i ++)
{
printf("第%d种:",i + 1);
scanf("%d",&bank.Available[i]);
printf("\n");
}
}
void InitRequest()
{
int i,s,j;
for(i = 0;i < bank.resource;i ++)
{
s = 0;
for( j = 0;j < bank.process;j ++)
{
s += bank.Allcation[j][i];
}
bank.Available[i] = bank.Available[i] - s;
}
}
int SafeSequence()
{
int i,j;
int flag,flag1;
i = k = 0;
while(k <= bank.process - 1)
{
flag = flag1 = 0;
if(i >= bank.process)
i = 0;
for(j = 0;j < bank.resource;j ++)
{
if(bank.Available[j] < bank.Need[i][j])
{
flag = 1;
break;
}
}
if(flag == 0 && vis[i] == 0)
{
vis[i] = 1;
SafeSeq[k ++] = i;
for(j = 0;j < bank.resource;j ++)
bank.Available[j] += bank.Allcation[i][j];
i = -1;
}
i ++;
}
return k;
}
int main()
{
int i,j;
int k;
memset(vis,0,sizeof(vis));
printf("请输入进程数:");
scanf("%d",&bank.process);
printf("请输入资源数:");
scanf("%d",&bank.resource);
InitResource();
ScanfResource();
InitRequest();
PrintfInfo();
k = SafeSequence();
printf("安全序列:");
for(i = 0;i < k;i ++)
printf("%d ",SafeSeq[i]);
return 0;
}
操作系统银行家算法(安全序列不唯一)
最新推荐文章于 2022-10-11 18:39:49 发布