首页主机资讯银行家算法 C语言实现

银行家算法 C语言实现

时间2023-11-20 23:15:04发布访客分类主机资讯浏览389
导读:以下是银行家算法在C语言中的实现:```c#include // 资源数量#define M 3// 进程数量#define N 5void calculateNeed(int need[N][M], int max[N][M], int...

以下是银行家算法在C语言中的实现:
```c
#include
// 资源数量
#define M 3
// 进程数量
#define N 5
void calculateNeed(int need[N][M], int max[N][M], int allocation[N][M]) {
for (int i = 0; i for (int j = 0; j need[i][j] = max[i][j] - allocation[i][j];
}
}
}
int isSafe(int available[M], int need[N][M], int allocation[N][M]) {
int finish[N] = { 0 } ;
int work[M];
for (int i = 0; i work[i] = available[i];
}
int count = 0;
while (count int found = 0;
for (int i = 0; i if (!finish[i]) {
int j;
for (j = 0; j if (need[i][j] > work[j]) {
break;
}
}
if (j == M) {
for (int k = 0; k work[k] += allocation[i][k];
}
finish[i] = 1;
found = 1;
count++;
}
}
}
if (!found) {
break;
}
}
if (count == N) {
return 1; // 安全
} else {
return 0; // 不安全
}
}
int main() {
int available[M] = { 3, 3, 2 } ;
int max[N][M] = { { 7, 5, 3 } , { 3, 2, 2 } , { 9, 0, 2 } , { 2, 2, 2 } , { 4, 3, 3 } } ;
int allocation[N][M] = { { 0, 1, 0 } , { 2, 0, 0 } , { 3, 0, 2 } , { 2, 1, 1 } , { 0, 0, 2 } } ;
int need[N][M];
calculateNeed(need, max, allocation);
if (isSafe(available, need, allocation)) {
printf("系统是安全的\n");
} else {
printf("系统是不安全的\n");
}
return 0;
}
```
以上代码实现了银行家算法的主要逻辑。输入的数据包括资源的数量、进程的数量、可用资源、最大需求矩阵和已分配矩阵。首先通过`calculateNeed`函数计算出需求矩阵。然后通过`isSafe`函数判断系统是否是安全的。如果是安全的,则输出"系统是安全的",否则输出"系统是不安全的"。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 银行家算法 C语言实现
本文地址: https://pptw.com/jishu/548120.html
css样式文字行距 css设置文字行高 ios开发模拟器大小设置 ios开发 模拟器

游客 回复需填写必要信息