银行家算法代码c++
时间: 2023-12-21 14:32:14 浏览: 37
银行家算法是一种用于避免死锁的资源分配算法。下面是一个简单的银行家算法的C++代码示例:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 定义进程的最大需求矩阵
vector<vector<int>> maxDemand = {{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}};
// 定义系统当前可用资源向量
vector<int> available = {3, 3, 2};
// 定义进程已分配资源矩阵
vector<vector<int>> allocation = {{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}};
// 定义进程还需要资源矩阵
vector<vector<int>> need(5, vector<int>(3));
// 定义进程数量和资源数量
int numProcesses = 5;
int numResources = 3;
// 初始化进程还需要资源矩阵
void initNeedMatrix() {
for (int i = 0; i < numProcesses; i++) {
for (int j = 0; j < numResources; j++) {
need[i][j] = maxDemand[i][j] - allocation[i][j];
}
}
}
// 检查进程是否满足资源需求
bool checkProcess(int process, vector<int>& work, vector<bool>& finish) {
for (int i = 0; i < numResources; i++) {
if (need[process][i] > work[i]) {
return false;
}
}
return true;
}
// 执行银行家算法
bool bankerAlgorithm() {
vector<int> work = available;
vector<bool> finish(numProcesses, false);
vector<int> safeSequence;
int count = 0;
while (count < numProcesses) {
bool found = false;
for (int i = 0; i < numProcesses; i++) {
if (!finish[i] && checkProcess(i, work, finish)) {
for (int j = 0; j < numResources; j++) {
work[j] += allocation[i][j];
}
finish[i] = true;
safeSequence.push_back(i);
found = true;
count++;
}
}
if (!found) {
return false;
}
}
cout << "Safe sequence: "; for (int i = 0; i < numProcesses; i++) {
cout << safeSequence[i] << " ";
}
cout << endl;
return true;
}
int main() {
initNeedMatrix();
if (bankerAlgorithm()) {
cout << "System is safe." << endl;
} else {
cout << "System is unsafe." << endl;
}
return 0;
}
```