操作系统银行家算法c++实现
#include<iostream>
using namespace std;
class process
{
public:
process()
{
Finish=false;
}
int Max[3]; //最大
int Allocation[3]; //已经分配的
int Need[3]; //需要的
bool Finish;
};
bool NeedWork(int *need,int*work)
{
for (int j=0;j<3;j++)
{
if (need[j]>work[j])
{
return false;
}
}
return true;
}
int main()
{
process p[5];
int a,b,c;
//输入Max
for(int i=0;i<5;i++)
{
cout<<"请输入第"<<i+1<<"个进程最大需要的资源:"<<endl;
cin>>a>>b>>c;
p[i].Max[0]=a;
p[i].Max[1]=b;
p[i].Max[2]=c;
}
//输入Allocation
for(i=0;i<5;i++)
{
cout<<"请输入第"<<i+1<<"个进程已经分配的资源:"<<endl;
cin>>a>>b>>c;
p[i].Allocation[0]=a;
p[i].Allocation[1]=b;
p[i].Allocation[2]=c;
}
//自动计算Need
cout<<"需要的资源:"<<endl;
for(i=0;i<5;i++)
{
p[i].Need[0]=p[i].Max[0]-p[i].Allocation[0];
p[i].Need[1]=p[i].Max[1]-p[i].Allocation[1];
p[i].Need[2]=p[i].Max[2]-p[i].Allocation[2];
cout<<p[i].Need[0]<<" ";
cout<<p[i].Need[1]<<" ";
cout<<p[i].Need[2]<<" ";
cout<<endl;
}
//输入可利用的资源 Available
int Available[3];
cout<<"可用的资源:"<<endl;
cin>>a>>b>>c;
Available[0]=a;
Available[1]=b;
Available[2]=c;
cout<<"哪个进程请求资源?:"<<endl;
int pr;
cin>>pr;
//输入请求的资源 Request
int Request[3];
cout<<"进程"<<pr<<"请求的资源:"<<endl;
cin>>a>>b>>c;
Request[0]=a;
Request[1]=b;
Request[2]=c;
for (i=0;i<3;i++)
{
if (Request[i]>p[pr].Need[i])
{
cout<<"请求的资源超过了申请的数量,不能分配!"<<endl;
return 0;
}
}
for (i=0;i<3;i++)
{
if (Request[i]>Available[i])
{
cout<<"请求的资源超过可利用的资源,不能分配!"<<endl;
return 0;
}
}
//尝试分配给请求的进程
for (int z=0;z<3;z++)
{
Available[z] =Available[z]-Request[z];
p[pr].Allocation[z]=p[pr].Allocation[z]+Request[z];
p[pr].Need[z]=p[pr].Need[z]-Request[z];
}
int Work[3];
Work[0]=Available[0];
Work[1]=Available[1];
Work[2]=Available[2];
int que[5];
for(int k=0;k<5;k++)
{
for(int x=0;x<5;x++)
{
//没有完成,并且资源充足
if(p[x].Finish==false && NeedWork(p[x].Need,Work) )
{
Work[0]+=p[x].Allocation[0];
Work[1]+=p[x].Allocation[1];
Work[2]+=p[x].Allocation[2];
p[x].Finish=true;
que[k]=x;
break;
}
}
}
int count=0;
for (int y=0;y<5;y++)
{
if (p[y].Finish==true)
{
count++;
}
}
if (count==5)
{
cout<<"可以分配,安全序列为:";
for (int quee=0;quee<5;quee++)
{
cout<<que[quee]<<",&quo
t;;
}
cout<<endl;
}
else
{
cout<<"不可以分配"<<endl;
//收回分配给请求的进程
for (int z=0;z<3;z++)
{
Available[z] =Av
操作系统银行家算法c++实现
ailable[z]+Request[z];
p[pr].Allocation[z]=p[pr].Allocation[z]-Request[z];
p[pr].Need[z]=p[pr].Need[z]+Request[z];
}
}
return 0;
}