#include "stdafx.h"
#include <iostream>
using namespace std;
#define M 5/*进程数*/
#define N 3/*资源数*/
#define False 0
#define True 1
int Available[N]={3,3,2};
int Max[M][N]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};
int Allocation[M][N]={{0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}};
int Need[M][N]={{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}};
void Showdata();
void Applydata();
int Check();
void main()
{
int n,i,j;
for ( i = 0; i < M; i++)
{
for ( j = 0; j < N; j++)
{
Need[i][j] = Max[i][j] - Allocation[i][j];
if (Need[i][j]<0)
{
j--;
continue;
}
}
}
while(1)
{
cout<<"****************************************************"<<endl;
cout<<"********************请选择操作**********************"<<endl;
cout<<"******1 申请资源 2 显示当前资源状态 3退出*****"<<endl;
cout<<"****************************************************"<<endl;
cin>>n;
switch(n)
{
case 1:
Applydata();
break;
case 2:
Showdata();
break;
default:
return;
}
}
}
void Applydata()
{
int i,j,flag=0,a=0,b=0;
int temp[N];
cout<<"输入进程的编号"<<endl;
cin>>i;
cout<<"输入每个资源的请求"<<endl;
for(j=0;j<N;j++)
{
cin>>temp[j];
}
for ( i = 0; i < N; i++)
{
if(temp[i]<=Need[a][i]){
if(temp[i]<=Available[i]){
flag++;
}
}
}
if(flag==N)
{
for(j=0;j<N;j++)
{
Available[j] -= temp[j];
Allocation[a][j] += temp[j];
Need[a][j] -= temp[j];
}
}
int wflag=Check();
if(wflag!=0)
{
cout<<"本次资源请求分配失败!!!"<<endl;
for(j=0;j<N;j++)
{
Available[j] += temp[j];
Allocation[a][j] -= temp[j];
Need[a][j] += temp[j];
}
}
else
{
cout<<"本次资源请求分配成功!";
cout<<endl<<endl;
}
}
int Check()
{
int Work[N],Finish[M],temp[M];
int i,j,m,k=0,count1=0,count2=0;
for(i=0;i<M;i++)
Finish[i]=false;
for(j=0;j<N;j++)
Work[j]=Available[j];
while(count2<M)
{
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
if( Finish[i]==false&&Need[i][j]<=Work[j]
)
count1++;
}
if(count1==N)
{
for(m=0;m<N;m++)
{
Work[m]+=Allocation[i][m];
}
Finish[i]=True;
temp[k]=i;
k++;
}
count1=0;
if (i==M-1)
{
count2++;
}
}
}
for(i=0;i<M;i++)
{
if(Finish[i]==false)
{
cout<<"系统处于不安全状态!!!"<<endl<<endl;
return 1;
}
}
cout<<endl<<"经安全性检查,系统处于安全状态"<<endl<<endl;
cout<<"本次安全序列:";
for(i=0;i<M;i++)
{
cout<<"进程"<<temp[i];
if(i<M-1)
cout<<"->";
}
cout<<endl;
return 0;
}
void Showdata()
{
int i,j;
cout<<" *****进程对各资源的最大需求Max*****"<<endl;
cout<<" 资源类别:R0 R1 R2"<<endl;
for(i=0;i<M;i++)
{
cout<<" "<<i<<"号进程:";
for(j=0;j<N;j++)
{
cout<<" "<<Max[i][j]<<" ";
}
cout<<endl;
}
cout<<endl<<endl;
cout<<" *****各进程已分配资源情况 Allocation *****"<<endl;
cout<<" 资源类别:R0 R1 R2"<<endl;
for(i=0;i<M;i++)
{
cout<<" "<<i<<"号进程:";
for(j=0;j<N;j++)
{
cout<<" "<<Allocation[i][j]<<" ";
}
cout<<endl;
}
cout<<endl<<endl;
cout<<" *********各进程还需要的资源量 Need *********"<<endl;
cout<<" 资源类别:R0 R1 R2"<<endl;
for(i=0;i<M;i++)
{
cout<<" "<<i<<"号进程:";
for(j=0;j<N;j++)
{
cout<<" "<<Need[i][j]<<" ";
}
cout<<endl;
}
cout<<endl<<endl;
cout<<" *****系统可用资源向量 Available *****"<<endl;
cout<<" 资源类别:R0 R1 R2"<<endl;
cout<<" 资源数目:";
for(j=0;j<N;j++)
cout<<Available[j]<<" ";
cout<<endl<<endl;
Check();
cout<<endl;
}