银行家算法和安全性算法c++代码 系统资源名称、系统资源数量、进程数量、各进程对资源的最大需求、各进程已申请到资源数等信息初始值不可以在程序中指定固定值,要在程序运行后人工输入。
时间: 2023-12-19 15:06:33 浏览: 60
下面是一个简单的 C++ 实现银行家算法和安全性算法的代码示例,包括输入系统资源名称、数量、进程数量、各进程对资源的最大需求、各进程已申请到资源数等信息。请注意,这只是一个简单的示例,实际情况下可能会有更复杂的实现。
```c++
#include <iostream>
#include <vector>
using namespace std;
const int MAX_RESOURCES = 5;
const int MAX_PROCESSES = 5;
vector<int> available(MAX_RESOURCES);
vector<vector<int>> maximum(MAX_PROCESSES, vector<int>(MAX_RESOURCES));
vector<vector<int>> allocation(MAX_PROCESSES, vector<int>(MAX_RESOURCES));
vector<vector<int>> need(MAX_PROCESSES, vector<int>(MAX_RESOURCES));
bool isSafe() {
vector<bool> finished(MAX_PROCESSES, false);
vector<int> work(available);
bool found = true;
while (found) {
found = false;
for (int i = 0; i < MAX_PROCESSES; i++) {
if (!finished[i]) {
bool enoughResources = true;
for (int j = 0; j < MAX_RESOURCES; j++) {
if (need[i][j] > work[j]) {
enoughResources = false;
break;
}
}
if (enoughResources) {
found = true;
finished[i] = true;
for (int j = 0; j < MAX_RESOURCES; j++) {
work[j] += allocation[i][j];
}
}
}
}
}
for (int i = 0; i < MAX_PROCESSES; i++) {
if (!finished[i]) {
return false;
}
}
return true;
}
bool requestResources(int pid, vector<int> request) {
for (int i = 0; i < MAX_RESOURCES; i++) {
if (request[i] > need[pid][i]) {
return false;
}
if (request[i] > available[i]) {
return false;
}
}
for (int i = 0; i < MAX_RESOURCES; i++) {
available[i] -= request[i];
allocation[pid][i] += request[i];
need[pid][i] -= request[i];
}
if (!isSafe()) {
for (int i = 0; i < MAX_RESOURCES; i++) {
available[i] += request[i];
allocation[pid][i] -= request[i];
need[pid][i] += request[i];
}
return false;
}
return true;
}
int main() {
// 输入系统资源名称、数量、进程数量、各进程对资源的最大需求、各进程已申请到资源数等信息
cout << "请输入系统资源数量: ";
for (int i = 0; i < MAX_RESOURCES; i++) {
cin >> available[i];
}
cout << "请输入进程数量: ";
int numProcesses;
cin >> numProcesses;
for (int i = 0; i < numProcesses; i++) {
cout << "请输入进程 " << i << " 最大需求资源数: ";
for (int j = 0; j < MAX_RESOURCES; j++) {
cin >> maximum[i][j];
need[i][j] = maximum[i][j];
}
cout << "请输入进程 " << i << " 已申请资源数: ";
for (int j = 0; j < MAX_RESOURCES; j++) {
cin >> allocation[i][j];
need[i][j] -= allocation[i][j];
}
}
// 执行银行家算法
if (isSafe()) {
cout << "系统处于安全状态" << endl;
} else {
cout << "系统处于不安全状态" << endl;
return 1;
}
// 执行安全性算法
cout << "请输入要请求资源的进程 ID: ";
int pid;
cin >> pid;
cout << "请输入进程 " << pid << " 请求的资源数: ";
vector<int> request(MAX_RESOURCES);
for (int i = 0; i < MAX_RESOURCES; i++) {
cin >> request[i];
}
if (requestResources(pid, request)) {
cout << "资源请求成功,系统仍处于安全状态" << endl;
} else {
cout << "资源请求失败,系统处于不安全状态" << endl;
}
return 0;
}
```
阅读全文