银行家算法模拟实验c语言
时间: 2023-11-16 10:00:34 浏览: 84
```c
#include <stdio.h>
#include <stdlib.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];
int work[MAX_RESOURCE];
int finish[MAX_PROCESS];
int request[MAX_RESOURCE];
int num_process, num_resource;
void init() {
int i, j;
printf("请输入进程数和资源数:\n");
scanf("%d%d", &num_process, &num_resource);
printf("请输入每个进程最大需求量:\n");
for (i = 0; i < num_process; i++) {
for (j = 0; j < num_resource; j++) {
scanf("%d", &max[i][j]);
}
}
printf("请输入每个进程已分配量:\n");
for (i = 0; i < num_process; i++) {
for (j = 0; j < num_resource; j++) {
scanf("%d", &allocation[i][j]);
need[i][j] = max[i][j] - allocation[i][j];
}
}
printf("请输入每个资源的总量:\n");
for (i = 0; i < num_resource; i++) {
scanf("%d", &available[i]);
}
}
int safety_check() {
int i, j, k;
for (i = 0; i < num_resource; i++) {
work[i] = available[i];
}
for (i = 0; i < num_process; i++) {
finish[i] = 0;
}
int count = 0;
while (count < num_process) {
int found = 0;
for (i = 0; i < num_process; i++) {
if (!finish[i]) {
int flag = 1;
for (j = 0; j < num_resource; j++) {
if (need[i][j] > work[j]) {
flag = 0;
break;
}
}
if (flag) {
found = 1;
finish[i] = 1;
count++;
for (k = 0; k < num_resource; k++) {
work[k] += allocation[i][k];
}
}
}
}
if (!found) {
return 0;
}
}
return 1;
}
int request_check(int pid) {
int i, j;
for (i = 0; i < num_resource; i++) {
if (request[i] > need[pid][i] || request[i] > available[i]) {
return 0;
}
}
for (i = 0; i < num_resource; i++) {
available[i] -= request[i];
allocation[pid][i] += request[i];
need[pid][i] -= request[i];
}
if (safety_check()) {
return 1;
} else {
for (i = 0; i < num_resource; i++) {
available[i] += request[i];
allocation[pid][i] -= request[i];
need[pid][i] += request[i];
}
return 0;
}
}
void request_resource() {
int pid, i;
printf("请输入请求资源的进程编号:\n");
scanf("%d", &pid);
printf("请输入请求的资源量:\n");
for (i = 0; i < num_resource; i++) {
scanf("%d", &request[i]);
}
if (request_check(pid)) {
printf("请求成功!\n");
} else {
printf("请求失败!\n");
}
}
int main() {
init();
if (safety_check()) {
printf("系统安全!\n");
} else {
printf("系统不安全!\n");
return 0;
}
while (1) {
printf("请输入要进行的操作:\n");
printf("1. 请求资源\n");
printf("2. 退出\n");
int op;
scanf("%d", &op);
if (op == 1) {
request_resource();
} else if (op == 2) {
break;
} else {
printf("无效操作!\n");
}
}
return 0;
}
```
阅读全文