银行家算法 C语言实现

avatar
作者
猴君
阅读量:1

以下是银行家算法在C语言中的实现:

#include <stdio.h> // 资源数量 #define M 3 // 进程数量 #define N 5 void calculateNeed(int need[N][M], int max[N][M], int allocation[N][M]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { need[i][j] = max[i][j] - allocation[i][j]; } } } int isSafe(int available[M], int need[N][M], int allocation[N][M]) { int finish[N] = { 0 }; int work[M]; for (int i = 0; i < M; i++) { work[i] = available[i]; } int count = 0; while (count < N) { int found = 0; for (int i = 0; i < N; i++) { if (!finish[i]) { int j; for (j = 0; j < M; j++) { if (need[i][j] > work[j]) { break; } } if (j == M) { for (int k = 0; k < M; k++) { work[k] += allocation[i][k]; } finish[i] = 1; found = 1; count++; } } } if (!found) { break; } } if (count == N) { return 1; // 安全 } else { return 0; // 不安全 } } int main() { int available[M] = { 3, 3, 2 }; int max[N][M] = { { 7, 5, 3 }, { 3, 2, 2 }, { 9, 0, 2 }, { 2, 2, 2 }, { 4, 3, 3 } }; int allocation[N][M] = { { 0, 1, 0 }, { 2, 0, 0 }, { 3, 0, 2 }, { 2, 1, 1 }, { 0, 0, 2 } }; int need[N][M]; calculateNeed(need, max, allocation); if (isSafe(available, need, allocation)) { printf("系统是安全的\n"); } else { printf("系统是不安全的\n"); } return 0; } 

以上代码实现了银行家算法的主要逻辑。输入的数据包括资源的数量、进程的数量、可用资源、最大需求矩阵和已分配矩阵。首先通过calculateNeed函数计算出需求矩阵。然后通过isSafe函数判断系统是否是安全的。如果是安全的,则输出"系统是安全的",否则输出"系统是不安全的"。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!