?? 多資源銀行家算法.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]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};
//系統可用資源數
int AVAILABLE[N]={10,5,7};
//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}};
int Request[N]={0,0,0};
void main()
{
int i=0,j=0;
char flag='Y';
void showdata();
void changdata(int);
void rstordata(int);
int chkerr(int);
showdata();
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<<"類資源的資源量!";
cout<<"申請不合理,出錯!請重新選擇!"<<endl;
flag='N';
break;
}
else
{
if(Request[j]>AVAILABLE[j])
{
cout<<" 進程"<<i<<"申請的資源數大于系統可用"<<j<<"類資源的資源量!";
cout<<"申請不合理,出錯!請重新選擇!"<<endl<<endl;
flag='N';
break;
}
}
}
if(flag=='Y'||flag=='y')
{
changdata(i);
if(chkerr(i))
{
rstordata(i);
showdata();
}
else
showdata();
}
else
showdata();
cout<<endl;
cout<<" 是否繼續銀行家算法演示,按'Y'或'y'鍵繼續,按'N'或'n'鍵退出演示: ";
cin>>flag;
}
}
void showdata()
{
int i,j;
cout<<"系統可用的資源數為:"<<endl<<endl;
cout<<" ";
for (j=0;j<N;j++)
cout<<" 資源"<<j<<": "<<AVAILABLE[j]<<endl;
cout<<" 各進程還需要的資源量:"<<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]<<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 chkerr(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<<" 本次安全序列:";
for(i=0;i<M;i++)cout<<"進程"<<temp[i]<<"->";
return 0;
};
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -