#include <iostream>
#include <string>
using namespace std;
int main() {
int maxNeed[1000]; // 最大需求
int allocate[1000]; //已分配
int available; //剩余可用资源
int finish[1000] = {0}; //表示系统是否有足够资源分配给进程
int n; //进程数量
cout << "请输入进程数量" << endl;
cin >> n;
for (int i = 0; i < n; i++) {
cout << "请输入P" << i << "进程的最大需求和已分配数" << endl;
cin >> maxNeed[i] >> allocate[i];
}
cout << "请输入剩余可用资源数量" << endl;
cin >> available;
int t = available;
//buffer: 保存执行过的进程
string buffer[1000];
string p = "p";
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (t >= (maxNeed[j] - allocate[j]) && finish[j] == 0) {
t += allocate[j];
finish[j] = 1;
buffer[count++] = p + to_string(j);
}
}
}
if (count == n) {
cout << "存在安全序列,执行顺序为:" << endl;
for (int i = 0; i < n - 1; i++) {
cout << buffer[i] << " -> ";
}
cout << buffer[n - 1];
cout << endl;
}
else {
cout << "无安全序列" << endl;
}
}
银行家算法 - 是否存在安全序列
最新推荐文章于 2024-03-10 02:35:18 发布