?? bank.cpp
字號:
#include "string.h"
#include "iostream.h"
#define M 5 //總進程數
#define N 3 //總資源數
#define FALSE 0
#define TRUE 1
//M個進程對N類資源最大資源需求量
int MAX[M][N]={{6,4,5},{2,5,1},{4,2,5},{3,2,4},{1,2,4}};
//系統可用資源數
int AVAILABLE[N]={11,5,6};
//M個進程已經得到N類資源的資源量
int ALLOCATION[M][N]={{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}};
//M個進程還需要N類資源的資源量
int NEED[M][N]={{6,4,5},{2,5,1},{4,2,5},{3,2,4},{1,2,4}};
int Request[N]={0,0,0};
void main()
{
int i=0,j=0;
char sign='Y';
void show_data(); //顯示出所有的數據
void up_data(int); //更新所有的數據
void rewrite_data(int); //重新更改所有的數據
int safe_chk(int); //執行安全性檢查
show_data();
while(sign=='Y'||sign=='y')
{
i=-1;
while(i<0||i>=M)
{
cout<<" 請輸入需要申請資源的進程號(從0到"<<M-1<<",如:1):";
cin>>i;
if(i<0||i>=M)cout<<" 您輸入的進程號不存在,請重新輸入!"<<endl;
}
cout<<" 請輸入進程"<<i<<"需要申請的資源數"<<endl;
for (j=0;j<N;j++)
{
cout<<" 資源"<<j<<": ";
cin>>Request[j];
if(Request[j]>NEED[i][j])
{
cout<<" 進程"<<i<<"申請的資源數大于進程"<<i<<"還需要"<<j<<"類資源的資源量!";
cout<<"申請不合理,請重新選擇!"<<endl<<endl;
sign='N';
break;
}
else
{
if(Request[j]>AVAILABLE[j])
{
cout<<" 進程"<<i<<"申請的資源數大于系統可用"<<j<<"類資源的資源量!";
cout<<"申請不合理,請重新選擇!"<<endl<<endl;
sign='N';
break;
}
}
}
if(sign=='Y'||sign=='y')
{
up_data(i);
if(safe_chk(i))
{
rewrite_data(i);
show_data();
}
else
show_data();
}
else
show_data();
cout<<endl;
cout<<" 按Y繼續銀行家算法,按N退出銀行家算法: ";
cin>>sign;
}
}
void show_data()
{
int i,j;
cout<<" ★★★★★★★★★★★★驗證銀行家算法★★★★★★★★★★★★"<<endl<<endl;
cout<<" 系統可用的資源數分別為:"<<endl<<endl;
cout<<" ";
for (j=0;j<N;j++)cout<<" 資源"<<j<<": "<<AVAILABLE[j];
cout<<endl;
cout<<endl;
cout<<" 各進程仍需要的資源量:"<<endl<<endl;
for (i=0;i<M;i++)
{
cout<<"進程"<<i<<":";
for (j=0;j<N;j++)cout<<" 資源"<<j<<": "<<NEED[i][j];
cout<<endl;
}
cout<<endl;
cout<<" 各進程已分配到的資源量: "<<endl<<endl;
for (i=0;i<M;i++)
{
cout<<"進程"<<i<<":";
for (j=0;j<N;j++)cout<<" 資源"<<j<<": "<<ALLOCATION[i][j];
cout<<endl;
}
cout<<endl;
};
void up_data(int k)
{
int j;
for (j=0;j<N;j++)
{
AVAILABLE[j]=AVAILABLE[j]-Request[j];
ALLOCATION[k][j]=ALLOCATION[k][j]+Request[j];
NEED[k][j]=NEED[k][j]-Request[j];
}
};
void rewrite_data(int k)
{
int j;
for (j=0;j<N;j++)
{
AVAILABLE[j]=AVAILABLE[j]+Request[j];
ALLOCATION[k][j]=ALLOCATION[k][j]-Request[j];
NEED[k][j]=NEED[k][j]+Request[j];
}
};
int safe_chk(int s)
{
int WORK,FINISH[M],temp[M];
int i,j,k=0;
for(i=0;i<M;i++)FINISH[i]=FALSE;
for(j=0;j<N;j++)
{
WORK=AVAILABLE[j];
i=s;
while(i<M)
{
if (FINISH[i]==FALSE&&NEED[i][j]<=WORK)
{
WORK=WORK+ALLOCATION[i][j];
FINISH[i]=TRUE;
temp[k]=i;
k++;
i=0;
}
else
{
i++;
}
}
for(i=0;i<M;i++)
if(FINISH[i]==FALSE)
{
cout<<endl;
cout<<" 系統不安全!!! 本次資源申請不成功!!!"<<endl;
cout<<endl;
return 1;
}
}
cout<<endl;
cout<<" 經安全性檢查,系統安全,本次分配成功。"<<endl;
cout<<endl;
cout<<" 本次安全序列為:";
for(i=0;i<M;i++)cout<<"進程"<<temp[i]<<"->";
cout<<endl<<endl;;
return 0;
};
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -