银行家算法C语言实现
时间: 2023-11-24 13:52:42 浏览: 95
以下是一个简单的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 num_process, num_resource;
bool is_safe() {
int work[MAX_RESOURCE];
for (int i = 0; i < num_resource; i++) {
work[i] = available[i];
}
bool finish_copy[MAX_PROCESS];
for (int i = 0; i < num_process; i++) {
finish_copy[i] = finish[i];
}
bool found;
do {
found = false;
for (int i = 0; i < num_process; i++) {
if (!finish_copy[i]) {
bool enough = true;
for (int j = 0; j < num_resource; j++) {
if (need[i][j] > work[j]) {
enough = false;
break;
}
}
if (enough) {
found = true;
finish_copy[i] = true;
for (int j = 0; j < num_resource; j++) {
work[j] += allocation[i][j];
}
}
}
}
} while (found);
for (int i = 0; i < num_process; i++) {
if (!finish_copy[i]) {
return false;
}
}
return true;
}
int main() {
printf("Enter the number of processes: ");
scanf("%d", &num_process);
printf("Enter the number of resources: ");
scanf("%d", &num_resource);
printf("Enter the available resources: ");
for (int i = 0; i < num_resource; i++) {
scanf("%d", &available[i]);
}
printf("Enter the maximum demand of each process: ");
for (int i = 0; i < num_process; i++) {
for (int j = 0; j < num_resource; j++) {
scanf("%d", &max[i][j]);
}
}
printf("Enter the allocation for each process: ");
for (int i = 0; i < num_process; i++) {
for (int j = 0; j < num_resource; j++) {
scanf("%d", &allocation[i][j]);
need[i][j] = max[i][j] - allocation[i][j];
}
}
if (is_safe()) {
printf("The system is safe.\n");
} else {
printf("The system is not safe.\n");
}
return 0;
}
```
阅读全文