📄 银行家.cpp
字号:
// 银行家.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream.h>
#define M 5 //总进程数
#define N 3 //总资源数
#define FALSE 0
#define TRUE 1
int MAX[M][N]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};//M个进程对N类资源最大资源需求量
int ALLOCATION[M][N]={{0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}};//M个进程已经得到N类资源的资源量
int NEED[M][N]={{7,4,3},{1,2,2},{6,0,0},{0,1,1},{4,3,1}};//M个进程还需要N类资源的资源量
int AVAILABLE[N]={3,3,2};//系统可用资源数
int Request[N]={0,0,0};
int proc[M]={0,1,2,3,4};
void show();
void safe(int);
void main()
{
int i=0;int j=0;
char flag='Y';
show();
while(flag=='Y'||flag=='y')
{
cout<<"请输入需要请求资源的进程号:";
cin>>i;
if (i<0||i>4) cout<<"输入的进程号不存在,请重新输入!"<<endl;
cout<<"请输入此进程需要申请的资源数:"<<endl;
for(j=0;j<3;j++)
{
cout<<"资源"<<j<<":";
cin>>Request[j];
if(Request[j]>NEED[i][j])
{
cout<<"进程"<<i<<"申请的资源数大于此进程所需第"<<j<<"类资源的资源量!";
cout<<"申请不合理,请重新选择!"<<endl<<endl;
flag='Y';
break;
}
if(Request[j]>AVAILABLE[j])
{
cout<<"进程"<<i<<"申请的资源数大于第"<<" "<<j<<" "<<"类资源可利用的资源量!";
cout<<"申请不合理,请重新选择!"<<endl<<endl;
flag='Y';
break;
}
}
if(Request[j]<NEED[i][j] && Request[j]<AVAILABLE[j]) continue;
safe(i);
cout<<endl;
cout<<"是否继续银行家算法演示,按'Y'或'y'键继续,按'N'或'n'键退出演示:";
cin>>flag;
}
}
void show()//显示已知
{
cout<<" "<<"MAX"<<" "<<"ALLOCATION"<<" "<<"NEED"<<endl;
for(int i=0;i<5;i++)
{
cout<<proc[i]<<" "<<MAX[i][0]<<' '<<MAX[i][1]<<' '<<MAX[i][2]<<" ";
cout<<ALLOCATION[i][0]<<' '<<ALLOCATION[i][1]<<' '<<ALLOCATION[i][2]<<" ";
cout<<NEED[i][0]<<' '<<NEED[i][1]<<' '<<NEED[i][2]<<endl;
}
cout<<"AVAILABLE:"<<" "<<AVAILABLE[0]<<" "<<AVAILABLE[1]<<" "<<AVAILABLE[2]<<endl;
};
void safe(int s)//安全检查
{
int WORK[N],FINISH[M],temp[M];
int i,j,k=0,count;
for(i=0;i<M;i++) FINISH[i]=FALSE;
for(j=0;j<N;j++) WORK[j]=AVAILABLE[j];
i=s;
while (i<M)
{
if(FINISH[i]==FALSE)
{
count=0;
for(j=0;j<N;j++)
{
if( NEED[i][j]>WORK[j]) count+=1;
else WORK[j]=WORK[j]+ALLOCATION[i][j];
}
if(count==0)
{
FINISH[i]=TRUE;
temp[k]=i;
k++;
i=0;
}
else {
for(j=0;j<N;j++) {if( NEED[i][j]<=WORK[j]) WORK[j]=WORK[j]-ALLOCATION[i][j];}
i++;}
}
else i++;
}
count=0;
for(i=0;i<M;i++)
if(FINISH[i]==FALSE) count+=1;
if( count!=0)
{
cout<<endl;
cout<<"系统不安全!!!本次资源申请不成功!!!"<<endl;
cout<<endl;
}
else{
cout<<endl;
cout<<"经安全性检验,系统安全,本次分配成功."<<endl;
cout<<endl;
cout<<" 本次安全序列:";
for(i=0;i<M;i++)cout<<"进程"<<temp[i]<<"->";
cout<<endl;}
};
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -