作業系統銀行家演算法(安全序列不唯一)
阿新 • • 發佈:2018-12-31
#include <stdio.h> #include <string.h> #define size 50 typedef struct bank { int process;//程序數 int resource;//資源數 int Max[size][size];//最大需求量 int Allcation[size][size];//已分配資源數 int Need[size][size];//還需資源數 int Available[size]; }Bank; Bank bank; int k = 0; int vis[size]; //標記陣列 int SafeSeq[size]; void ScanfResource() { int i,j; for(i = 0;i < bank.process;i ++) { printf("----------第%d程序----------\n",i + 1); printf("最大資源量:",i + 1); for(j = 0;j < bank.resource;j ++) { scanf("%d",&bank.Max[i][j]); } printf("\n"); printf("已分配資源量:",i + 1); for(j = 0;j < bank.resource;j ++) { scanf("%d",&bank.Allcation[i][j]); } for(j = 0;j < bank.resource;j ++) { bank.Need[i][j] = bank.Max[i][j] - bank.Allcation[i][j]; } if(i == bank.process - 1 ) printf("--------------------------------\n"); } } void PrintfInfo() { int i,j; printf("程序\t最大資源量\t已分配資源量\t還需資源量\n"); for(i = 0;i < bank.process;i ++) { printf("%d\t",i + 1); for(j = 0;j < bank.resource;j ++) { if(j == bank.resource - 1) printf("%d \t",bank.Max[i][j]); else printf("%d ",bank.Max[i][j]); } for(j = 0;j < bank.resource;j ++) { if(j == bank.resource - 1) printf("%d \t",bank.Allcation[i][j]); else printf("%d ",bank.Allcation[i][j]); } for(j = 0;j < bank.resource;j ++) { if(j == bank.resource - 1) printf("%d",bank.Need[i][j]); else printf("%d ",bank.Need[i][j]); } printf("\n"); } } void InitResource() { int i,j; int s; printf("請輸入每種資源的數量:\n"); for(i = 0;i < bank.resource;i ++) { printf("第%d種:",i + 1); scanf("%d",&bank.Available[i]); printf("\n"); } } void InitRequest() { int i,s,j; for(i = 0;i < bank.resource;i ++) { s = 0; for( j = 0;j < bank.process;j ++) { s += bank.Allcation[j][i]; } bank.Available[i] = bank.Available[i] - s; } } int SafeSequence() { int i,j; int flag,flag1; i = k = 0; while(k <= bank.process - 1) { flag = flag1 = 0; if(i >= bank.process) i = 0; for(j = 0;j < bank.resource;j ++) { if(bank.Available[j] < bank.Need[i][j]) { flag = 1; break; } } if(flag == 0 && vis[i] == 0) { vis[i] = 1; SafeSeq[k ++] = i; for(j = 0;j < bank.resource;j ++) bank.Available[j] += bank.Allcation[i][j]; i = -1; } i ++; } return k; } int main() { int i,j; int k; memset(vis,0,sizeof(vis)); printf("請輸入程序數:"); scanf("%d",&bank.process); printf("請輸入資源數:"); scanf("%d",&bank.resource); InitResource(); ScanfResource(); InitRequest(); PrintfInfo(); k = SafeSequence(); printf("安全序列:"); for(i = 0;i < k;i ++) printf("%d ",SafeSeq[i]); return 0; }