?? 銀行家算法.cpp
字號:
#include "string.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}};
int AVAILABLE[N]={10,5,7};
int ALLOCATION[M][N]={{0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}};
int NEED[M][N]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};
int Request[N]={0,0,0};
void main()
{
int i=0,j=0;
char flag='Y';
void show();
void changdata(int);
void rstordata(int);
int check(int);
show();
//while(flag=='Y'||flag=='y')
//{
i=-1;
while(i<0||i>=M)
{
cout<<"請輸入需申請資源的進程號(從0到"<<M-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<<"類資源的資源量!"<<endl;
cout<<"申請失敗!";
flag='N';
break;
}
else
{
if(Request[j]>AVAILABLE[j])
{
cout<<" 進程"<<i<<"申請的資源數大于系統可用"<<j<<"類資源的資源量!"<<endl;
cout<<"申請失敗!";
flag='N';
break;
}
}
}
if(flag=='Y'||flag=='y')
{
changdata(i);
if(check(i))
{
rstordata(i);
show();
}
else
show();
}
//else
//showdata();
//cout<<endl;
//cout<<" 是否繼續銀行家算法演示,按'Y'或'y'鍵繼續,按'N'或'n'鍵退出演示: ";
//cin>>flag;
//}
}
void show()
{
int i,j;
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 changdata(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 rstordata(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 check(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;
}
}
for(i=0;i<M;i++)
if(FINISH[i]==TRUE)
{
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 + -