代码有问题,见谅!
#include <stdio.h>#include <stdlib.h>#include<time.h>#define randomize() srand((unsigned)time(NULL)) //定义一个宏#define uint unsigned int#define uchar unsigned char#define RES 3 //系统资源数#define MAX_P 5 //进程数//PCB结构体定义部分typedef struct PCB{ /* 进程标识符 */ uint id; /* 每一个进程需求M类资源的最大数目 */ uint max[RES]; /* 已分配的资源数 */ uint allocation[RES]; /* 当前进程还需要的资源个数 */ uint need[RES]; /* 当前进程请求资源 */ uint request[RES]; /* 标志进程是否可执行完成 */ uint finish;};/* 系统中R资源的个数 */uint available[RES];uint work[RES];uchar finish[RES],flag;struct PCB process[MAX_P];void init(void);bool check(void);void out();void main(void) ///主函数/{ int i,j; init(); printf("===============banker===============\n"); out(); while(!flag) { randomize(); //随机函数 for(i=0;i<MAX_P;i++) { process[i].finish = 0; for(j=0;j<RES;j++) { process[i].request[j] = rand()%5;//i进程申请j资源随机个 if(process[i].request[j] < process[i].need[j]) if(process[i].request[j] < available[j]) { work[j] = available[j]; //finish = 0; if(check()) //安全性检查 { available[j] = available[j] - process[i].request[j]; process[i].allocation[j] = process[i].allocation[j] + process[i].request[j]; process[i].need[j] = process[i].need[j] - process[i].request[j]; printf("distribute....\n"); out(); flag = 1; } else printf("wait...\n"); } else printf("wait...\n"); else printf(".....error...\n"); } } for(i=0;i<MAX_P;i++) for(j=0;j<RES;j++) { } }}void out(void){ //printf("##############资源情况###################\n"); printf("\n进程\tMax\tAllocation\tNeed\tAvailable\tFinish\n"); printf("----------------------------------------------------------------|\n"); int i; for(i=0;i<MAX_P;i++) { printf("%d\t%d,%d,%d\t%d,%d,%d\t\t%d,%d,%d\t%d,%d,%d\t\t%d |\n",process[i].id,process[i].max[0],process[i].max[1],process[i].max[2],process[i].allocation[0],process[i].allocation[1],process[i].allocation[2],process[i].need[0],process[i].need[1],process[i].need[2],available[0],available[1],available[2],process[i].finish); if(i==4) printf("----------------------------------------------------------------|\n"); }}/* 安全性检查 */bool check(void){ int i,j; for(i=0;i<MAX_P;i++) for(j=0;j<RES;j++) { if(!process[i].finish && process[i].need[j]<=work[j]) { work[j] += process[i].allocation[j]; process[i].finish = 1; printf("...not safe....\n"); } else printf("...not safe....\n"); } out(); return true;}/** 初始化 **/void init(void){ int i = 0; int j = 0; flag = 0; randomize(); //随机产生各资源的个数 for(i=0;i<RES;i++) available[i] = rand()%5+6; //初始化各进程 for(i=0;i<MAX_P;i++) { //初始化进程ID process[i].id = i+1; //各进程对资源的最大需求,随机产生:0~10 //已分配0个资源 //请求资源0个 //尚需 max - allocation for(j=0;j<RES;j++) { process[i].max[j] = rand()%10; process[i].allocation[j] = 0; process[i].request[j] = 0; process[i].need[j] = process[i].max[j]-process[i].allocation[j]; } }}
相关资源:C语言实现银行家算法