银行家算法代码c语言版
时间: 2023-10-13 11:16:30 浏览: 80
以下是银行家算法的C语言实现示例:
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_PROCESS 10
#define MAX_RESOURCE 10
int allocation[MAX_PROCESS][MAX_RESOURCE];
int max[MAX_PROCESS][MAX_RESOURCE];
int need[MAX_PROCESS][MAX_RESOURCE];
int available[MAX_RESOURCE];
bool finish[MAX_PROCESS];
int num_process, num_resource;
void input()
{
printf("Enter number of processes: ");
scanf("%d", &num_process);
printf("Enter number of resources: ");
scanf("%d", &num_resource);
printf("Enter allocation matrix:\n");
for (int i = 0; i < num_process; i++) {
for (int j = 0; j < num_resource; j++) {
scanf("%d", &allocation[i][j]);
}
}
printf("Enter max matrix:\n");
for (int i = 0; i < num_process; i++) {
for (int j = 0; j < num_resource; j++) {
scanf("%d", &max[i][j]);
}
}
printf("Enter available resources:\n");
for (int i = 0; i < num_resource; i++) {
scanf("%d", &available[i]);
}
}
void calculate_need()
{
for (int i = 0; i < num_process; i++) {
for (int j = 0; j < num_resource; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
}
bool is_safe()
{
int work[MAX_RESOURCE];
for (int i = 0; i < num_resource; i++) {
work[i] = available[i];
}
for (int i = 0; i < num_process; i++) {
finish[i] = false;
}
int count = 0;
while (count < num_process) {
bool found = false;
for (int i = 0; i < num_process; i++) {
if (!finish[i]) {
bool can_execute = true;
for (int j = 0; j < num_resource; j++) {
if (need[i][j] > work[j]) {
can_execute = false;
break;
}
}
if (can_execute) {
for (int j = 0; j < num_resource; j++) {
work[j] += allocation[i][j];
}
finish[i] = true;
found = true;
count++;
}
}
}
if (!found) {
return false;
}
}
return true;
}
int main()
{
input();
calculate_need();
if (is_safe()) {
printf("Safe sequence: ");
int seq[MAX_PROCESS];
int k = 0;
int count = 0;
while (count < num_process) {
for (int i = 0; i < num_process; i++) {
if (!finish[i]) {
bool can_execute = true;
for (int j = 0; j < num_resource; j++) {
if (need[i][j] > available[j]) {
can_execute = false;
break;
}
}
if (can_execute) {
for (int j = 0; j < num_resource; j++) {
available[j] += allocation[i][j];
}
finish[i] = true;
seq[k++] = i;
count++;
break;
}
}
}
}
for (int i = 0; i < num_process; i++) {
printf("%d ", seq[i]);
}
printf("\n");
} else {
printf("Unsafe state\n");
}
return 0;
}
```
在这个示例中,我们首先输入了进程数和资源数,然后输入了分配矩阵,最大需求矩阵和可用资源向量。然后我们计算出需要矩阵,并使用银行家算法来检查系统是否处于安全状态。如果系统处于安全状态,我们打印出安全序列。否则,我们打印出不安全状态。
阅读全文