银行家算法代码c语言实现
时间: 2023-11-16 09:02:06 浏览: 172
下面是银行家算法的C语言实现代码:
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_PROCESS 10
#define MAX_RESOURCE 10
int available[MAX_RESOURCE];
int max[MAX_PROCESS][MAX_RESOURCE];
int allocation[MAX_PROCESS][MAX_RESOURCE];
int need[MAX_PROCESS][MAX_RESOURCE];
bool finish[MAX_PROCESS];
int n, m;
bool is_safe() {
int work[MAX_RESOURCE];
for (int i = 0; i < m; i++) {
work[i] = available[i];
}
bool finish_copy[MAX_PROCESS];
for (int i = 0; i < n; i++) {
finish_copy[i] = finish[i];
}
bool flag = true;
while (flag) {
flag = false;
for (int i = 0; i < n; i++) {
if (!finish_copy[i]) {
bool temp_flag = true;
for (int j = 0; j < m; j++) {
if (need[i][j] > work[j]) {
temp_flag = false;
break;
}
}
if (temp_flag) {
for (int j = 0; j < m; j++) {
work[j] += allocation[i][j];
}
finish_copy[i] = true;
flag = true;
}
}
}
}
for (int i = 0; i < n; i++) {
if (!finish_copy[i]) {
return false;
}
}
return true;
}
int main() {
printf("请输入进程数和资源数:\n");
scanf("%d%d", &n, &m);
printf("请输入每个进程最大需求量:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &max[i][j]);
}
}
printf("请输入每个进程已分配量:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%d", &allocation[i][j]);
need[i][j] = max[i][j] - allocation[i][j];
}
}
printf("请输入每个资源的可用量:\n");
for (int i = 0; i < m; i++) {
scanf("%d", &available[i]);
}
if (is_safe()) {
printf("系统是安全的!\n");
} else {
printf("系统是不安全的!\n");
}
return 0;
}
```
阅读全文