#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define m_size 3
#define n_size 5
int Available[m_size]={3,3,2};
int Max[n_size][m_size]={7,5,3,3,2,2,9,0,2,2,2,2,4,3,3};
int Allocation[n_size][m_size]={0,1,0,2,0,0,3,0,2,2,1,1,0,0,2};
int Need[n_size][m_size];
int main(){
//已知条件:max与allocation
for(int i=0;i<5;i++){
for(int j=0;j<3;j++){
Need[i][j]=Max[i][j]-Allocation[i][j];
}
}
//打印目前的资源分配情况
cout<<"Available:";
for(int j=0;j<3;j++)
cout<<Available[j]<<" ";
cout<<endl;
for(int i=0;i<5;i++){
cout<<"P"<<i<<" ";
for(int j=0;j<3;j++){
cout<<Max[i][j]<<" ";
}
for(int j=0;j<3;j++){
cout<<Allocation[i][j]<<" ";
}
for(int j=0;j<3;j++){
cout<<Need[i][j]<<" ";
}
cout<<endl;
}
int Request[m_size];
int request;
int newi;
cout<<"请输入要请求的进程号和其请求向量" ;
cin>>newi;
for(int i=0;i<3;i++){
cin>>Request[i];
}
for(int j=0;j<3;j++){
if(Request[j]<=Need[newi][j]){
if(Request[j]<=Available[j]){
//三修改
Available[j]=Available[j]-Request[j];
Allocation[newi][j]+=Request[j];
Need[newi][j]=Need[newi][j]-Request[j];
//cout<<"修改啦!"<<endl;
}
else{
cout<<"尚无足够资源,需等待"<<endl;
return 0;
}
}
else{
cout<<"需要的资源数已经超过了最大值"<<endl;
return 0;
}
}
// 至此 √√√
//安全性算法
int safe[5];
bool finish[5] = { false,false, false, false, false };
int work[m_size];
for(int j=0;j<3;j++){
work[j]=Available[j];
}
int flag=1;//通过
int jilu;
int f1;
int cnt=0;
step2:
for(int i=0;i<5;i++){
for(int j=0;j<3;j++){
if(Need[i][j]>work[j]){
flag=1;
}
}
if(finish[i]==false && flag==1){
//Pi加入安全序列
safe[cnt]=jilu;
cnt++;
finish[i]=true;
jilu=i;
goto step3;
}
else{
goto step4;
}
step3:
for(int j=0;j<3;j++){
work[j]=work[j]+Allocation[jilu][j];
}
goto step2;
step4:
f1=1;
for(int i=0;i<5;i++){
if(finish[i]==false){
f1=0;
}
}
}
if(f1==1){
cout<<"系统处于安全状态"<<endl;
for(int k=0;k<5;k++){
cout<<"安全序列为"<<safe[k]<<" ";
}
}
else if(f1==0){
cout<<"不安全状态"<<endl;
}
return 0;
}
上面是我的代码 现在出现的问题是输出的安全序列一直是“0 1 2 3 4” 不知道怎么改了 检查了好多遍 请各位前辈帮忙改改!
C++银行家算法完整实例:
https://www.cnblogs.com/tlnshuju/p/7069482.html
我自己感觉是安全性算法那里有一些问题 但迷惑了好久不知道怎么改 刚刚学操作系统这里
您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!
速戳参与调研>>>https://t.csdnimg.cn/Kf0y