实验目标:
- 已知分配矩阵、最大需求矩阵和可用资源向量,编写程序,求一个安全序列,并判断系统是否安全
实验设备:
- 硬件:微机,hyper-V虚拟化平台或者远程linux终端
- 软件:gcc
1、已知分配矩阵、最大需求矩阵和可用资源向量,编写一个程序,求安全序列,并判断系统是否安全
提示:根据课件上的银行家算法,写个程序。已知条件可以通过数组赋初值的方式
【代码】
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAX_PROCESS 5
#define MAX_RESOURCE 3
// 函数声明
bool isSafe(int available[], int max[][MAX_RESOURCE], int allocation[][MAX_RESOURCE], int need[][MAX_RESOURCE], int n, int m, int safeSequence[]);
void calculateNeed(int max[][MAX_RESOURCE], int allocation[][MAX_RESOURCE], int need[][MAX_RESOURCE], int n, int m);
int main() {
// 可用资源向量
int available[MAX_RESOURCE] = {3, 3, 2};
// 最大需求矩阵
int max[MAX_PROCESS][MAX_RESOURCE] = {
{7, 5, 3},
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}
};
// 已分配矩阵
int allocation[MAX_PROCESS][MAX_RESOURCE] = {
{0, 1, 0},
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}
};
// 需求矩阵
int need[MAX_PROCESS][MAX_RESOURCE];
int n = 5; // 进程数
int m = 3; // 资源种类数
int safeSequence[MAX_PROCESS]; // 用于存储安全序列
// 计算需求矩阵
calculateNeed(max, allocation, need, n, m);
// 检查系统是否安全
if (isSafe(available, max, allocation, need, n, m, safeSequence)) {
printf("The system is in a safe state\n");
printf("Safe sequence:");
for (int i = 0; i < n; i++) {
if (i > 0) {
printf(", ");
}
printf("P%d", safeSequence[i] + 1); // 进程编号从 P1 开始
}
printf("\n");
} else {
printf("The system is in an unsafe state\n");
}
return 0;
}
// 计算需求矩阵
void calculateNeed(int max[][MAX_RESOURCE], int allocation[][MAX_RESOURCE], int need[][MAX_RESOURCE], int n, int m) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
}
// 检查系统是否安全
bool isSafe(int available[], int max[][MAX_RESOURCE], int allocation[][MAX_RESOURCE], int need[][MAX_RESOURCE], int n, int m, int safeSequence[]) {
int work[MAX_RESOURCE];
bool finish[MAX_PROCESS] = {false}; // 初始化所有进程为未完成
int index = 0; // 安全序列索引
// 初始化工作向量为可用资源
for (int i = 0; i < m; i++) {
work[i] = available[i];
}
// 尝试找到安全序列
for (int count = 0; count < n; count++) {
bool found = false;
// 按 P1 - P5 顺序依次检查
for (int p = 0; p < n; p++) {
if (!finish[p]) { // 如果进程尚未完成
bool possible = true;
// 检查当前进程的需求是否小于等于可用资源
for (int r = 0; r < m; r++) {
if (need[p][r] > work[r]) {
possible = false;
break;
}
}
if (possible) {
// 如果可以满足需求,将进程加入安全序列
for (int r = 0; r < m; r++) {
work[r] += allocation[p][r]; // 释放该进程占用的资源
}
safeSequence[index++] = p; // 记录安全序列
finish[p] = true; // 标记进程为已完成
found = true;
break; // 找到一个可执行进程,跳出内层循环
}
}
}
if (!found) {
return false; // 如果没有找到可执行的进程,系统不安全
}
}
return true; // 找到安全序列,系统安全
}
【过程】
①输入gcc test.c -o test和./test。
②输出如下,这里只输出了一种可能性。
③验证,更改相关最大需求量如下图。(找不到安全序列的例子)
输出如下图,找不到安全序列。
【结论】
银行家算法作为一种经典的死锁避免算法,在多进程资源分配场景中有着至关重要的作用。它通过提前检查资源分配是否会使系统进入不安全状态,从而决定是否分配资源,从源头上避免了死锁的产生。在实际的操作系统和资源管理系统里,这种算法能够显著提升系统的稳定性和可靠性,保证多个进程可以安全、高效地共享有限的资源。