操作系统死锁避免实验c语言代码
时间: 2023-12-14 20:32:45 浏览: 118
根据提供的引用内容,可以介绍一下《操作系统》第四版汤小丹等人编著的C语言代码实现银行家算法。代码可以自行设置进程相关数据,显示安全序列,可以多次申请资源查看是否安全。以下是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define N 100
#define M 100
int available[M], max[N][M], allocation[N][M], need[N][M], request[M], finish[N], work[M], safe[N];
int n, m, num = 0;
void init() {
int i, j;
printf("请输入进程数n和资源种类数m:\n");
scanf("%d%d", &n, &m);
printf("请输入每个进程最大需求矩阵:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
scanf("%d", &max[i][j]);
}
}
printf("请输入每个进程已分配矩阵:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
scanf("%d", &allocation[i][j]);
}
}
printf("请输入每个进程还需要矩阵:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
printf("请输入每个资源可用数:\n");
for (i = 0; i < m; i++) {
scanf("%d", &available[i]);
}
}
void show() {
int i, j;
printf("进程数n=%d, 资源种类数m=%d\n", n, m);
printf("每个进程最大需求矩阵:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("%d ", max[i][j]);
}
printf("\n");
}
printf("每个进程已分配矩阵:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("%d ", allocation[i][j]);
}
printf("\n");
}
printf("每个进程还需要矩阵:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("%d ", need[i][j]);
}
printf("\n");
}
printf("每个资源可用数:\n");
for (i = 0; i < m; i++) {
printf("%d ", available[i]);
}
printf("\n");
}
int safety() {
int i, j, k, flag, count = 0;
for (i = 0; i < n; i++) {
finish[i] = 0;
}
for (i = 0; i < m; i++) {
work[i] = available[i];
}
while (count < n) {
flag = 0;
for (i = 0; i < n; i++) {
if (finish[i] == 0) {
for (j = 0; j < m; j++) {
if (need[i][j] > work[j]) {
break;
}
}
if (j == m) {
for (k = 0; k < m; k++) {
work[k] += allocation[i][k];
}
finish[i] = 1;
safe[count] = i;
count++;
flag = 1;
}
}
}
if (flag == 0) {
return 0;
}
}
return 1;
}
void request_res() {
int i, j, p;
printf("请输入请求资源的进程编号:\n");
scanf("%d", &p);
printf("请输入请求资源向量:\n");
for (i = 0; i < m; i++) {
scanf("%d", &request[i]);
}
for (i = 0; i < m; i++) {
if (request[i] > need[p][i]) {
printf("请求资源大于进程还需要的资源!\n");
return;
}
if (request[i] > available[i]) {
printf("请求资源大于系统可用的资源!\n");
return;
}
}
for (i = 0; i < m; i++) {
available[i] -= request[i];
allocation[p][i] += request[i];
need[p][i] -= request[i];
}
if (safety() == 1) {
printf("同意分配请求!\n");
} else {
printf("拒绝分配请求!\n");
for (i = 0; i < m; i++) {
available[i] += request[i];
allocation[p][i] -= request[i];
need[p][i] += request[i];
}
}
}
int main() {
int i;
init();
show();
if (safety() == 1) {
printf("系统是安全的!\n");
printf("安全序列为:");
for (i = 0; i < n; i++) {
printf("%d ", safe[i]);
}
printf("\n");
} else {
printf("系统是不安全的!\n");
}
request_res();
return 0;
}
```
阅读全文