?? 銀行家.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 + -