银行家算法C++简单实现
时间: 2024-06-03 10:05:58 浏览: 14
银行家算法是避免死锁的著名算法。以下是C++的简单实现:
```c++
#include <iostream>
using namespace std;
const int P = 5; // 定义进程数
const int R = 3; // 定义资源数
void calculateNeed(int need[P][R], int maxm[P][R], int allot[P][R]);
bool isSafe(int processes[], int avail[], int maxm[][R], int allot[][R]);
int main()
{
int processes[P] = { 0, 1, 2, 3, 4 }; // 定义进程数组
int avail[R] = { 3, 3, 2 }; // 定义资源数组
int maxm[P][R] = { { 7, 5, 3 }, { 3, 2, 2 }, { 9, 0, 2 }, { 2, 2, 2 }, { 4, 3, 3 } }; // 定义最大需求矩阵
int allot[P][R] = { { 0, 1, 0 }, { 2, 0, 0 }, { 3, 0, 2 }, { 2, 1, 1 }, { 0, 0, 2 } }; // 定义已分配矩阵
int need[P][R]; // 定义需求矩阵
calculateNeed(need, maxm, allot);
if (isSafe(processes, avail, maxm, allot))
cout << "系统是安全的" << endl;
else
cout << "系统是不安全的" << endl;
return 0;
}
// 计算需求矩阵
void calculateNeed(int need[P][R], int maxm[P][R], int allot[P][R])
{
for (int i = 0; i < P; i++)
for (int j = 0; j < R; j++)
need[i][j] = maxm[i][j] - allot[i][j];
}
// 判断系统是否是安全的
bool isSafe(int processes[], int avail[], int maxm[][R], int allot[][R])
{
int need[P][R];
calculateNeed(need, maxm, allot);
bool finish[P] = { 0 };
int safeSeq[P];
int work[R];
for (int i = 0; i < R; i++)
work[i] = avail[i];
int count = 0;
while (count < P)
{
bool found = false;
for (int i = 0; i < P; i++)
{
if (!finish[i])
{
int j;
for (j = 0; j < R; j++)
if (need[i][j] > work[j])
break;
if (j == R)
{
for (int k = 0; k < R; k++)
work[k] += allot[i][k];
safeSeq[count++] = i;
finish[i] = true;
found = true;
}
}
}
if (!found)
return false;
}
return true;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)