📄 yinhangjiasuanfa.cpp
字号:
#include "iostream.h"
#include"stdlib.h"
#define N 5
int available[3]={3,3,2};
int max[6][3]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};
int allocation[6][3]={{0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}};
int need[6][3]={{7,4,3},{1,2,2},{6,0,0},{0,1,1},{4,3,1}};
int stay[3][3];
int request[3],process[5];
int i,j,p,kk,h=-1;//h为除去的进程号
void tu()
{
cout<<"----------------资源分配表-----------------"<<endl;
cout<<" Max Allocation Need Available"<<endl;
cout<<"PRO A B C A B C A B C A B C"<<endl;
for(i=0;i<N;i++)
{
if(i!=h)
{
cout<<"P"<<i<<" ";
for(j=0;j<=2;j++)
cout<<max[i][j]<<" ";
cout<<" ";
for(j=0;j<=2;j++)
cout<<allocation[i][j]<<" ";
cout<<" ";
for(j=0;j<=2;j++)
cout<<need[i][j]<<" ";
cout<<" ";
if(i==0)
cout<<available[0]<<" "<<available[1]<<" "<<available[2];
cout<<endl;
}
}
cout<<"------------------------------------------"<<endl;
}
int run()
{
int a=1;
for(i=0;i<=2;i++)
{
if(need[p][i]<request[i])
{
a=0;break;
}
if(available[i]<request[i])
{
a=0;break;
}
}
if(a==1)
{
for(i=0;i<=2;i++)
{
stay[0][i]=allocation[p][i];
allocation[p][i]+=request[i];
stay[1][i]=need[p][i];
need[p][i]-=request[i];
stay[2][i]=available[i];
available[i]-=request[i];
}
}
return(a);
}
int test()
{
int work[3],finish[5]={0,0,0,0,0},a,k=0,t=0;
for(i=0;i<N;i++)
if((h>=0)&&(i==h))
{
finish[i]=1; kk=kk-1;
}
for(i=0;i<=2;i++)
work[i]=available[i];
while(1)
{
for(i=0;i<=4;i++)
{
if(finish[i]==0)
{
a=1;
for(j=0;j<=2;j++)
if(need[i][j]>work[j])
{
a=0; break;
}
if(a==1)
{
finish[i]=1;
for(j=0;j<=2;j++)
work[j]+=allocation[i][j];
process[k]=i;k++;
}
}
}
if(t==k) break; //循环一圈无可执行进程,阻塞跳出结束
else t=k;
if(k==kk) break;
}
if(k==kk) return(1);
else return(0);
}
void main()
{
tu();
while(1)
{
int l=1;
kk=N;
while(l)
{
cout<<"*******************************************"<<endl;
cout<<"输入选择的进程(P0-P5)[-1结束]:进程P";
cin>>p;
if(p==-1) { cout<<"退出..."<<endl; exit(0);}
if(!(p<0||p>4||p==h)&&(p!=-1))
{
cout<<"需求A资源:";cin>>request[0];
cout<<"需求B资源:";cin>>request[1];
cout<<"需求C资源:";cin>>request[2];
l=0;
}
if(l==1) cout<<"选择进程错误,重新输入!"<<endl;
}
if(run()==0)
{
cout<<"资源缺乏或需求错误!"<<"进程P"<<p<<"等待..."<<endl;
cout<<"继续..."<<endl;
}
else if(test()==0)
{
cout<<"系统进入不安全状态!"<<"进程"<<p<<"等待..."<<endl;
cout<<"继续..."<<endl;
for(i=0;i<=2;i++)
{
allocation[p][i]=stay[0][i];
need[p][i]=stay[1][i];
available[i]=stay[2][i];
}
}
else
{
tu();
cout<<"系统安全,存在安全序列:";
for(i=0;i<kk-1;i++)
cout<<"P"<<process[i]<<"->";
cout<<"P"<<process[kk-1]<<
endl;
}
if(need[p][0]==0&&need[p][1]==0&&need[p][2]==0)
{
for(i=0;i<=2;i++)
{
available[i]+=max[p][i];
}
h=p;
cout<<"释放进程P"<<p<<"资源"<<endl;
tu();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -