本文共 2129 字,大约阅读时间需要 7 分钟。
操作系统 银行家算法模拟实现
这个是我的课程设计内容,我把我写的代码贴出来作参考。我会分成几部分更新,也会写每个函数的思路。最后会放出完整代码。
这个课程设计主要就是银行家算法的实现,最核心的就是模拟分配,若程序任然安全就完成此次分配,否则就撤回分配,返回之前的安全状态。我用的是C语言实现的。
功能函数:
1 判断当前资源是否安全的功能函数
思路:
1) 先将需要判断的进程放在一个集合ProcessSet中,也就是不需要的进程置为-1即ProcessSet[i] = OUT,再将系统可用资源数拷贝一份CurrentAvailable
2)寻找进程中是否有符合进程需要的资源<= 系统可用资源(need[j] <= CurrentAvailable),若有将系统资源数加上该进程已分配的资源数CurrentAvailable += allocation[j],
还要将该进程置为-1即ProcessSet[i] = OUT,若找不到执行第三步,若找到继续执行第二步。
3)判断进程是否都执行完成,若都完成返回安全,否则返回不安全
//判断是否安全 int isSafe(int process_count,int source_count,int **allocation,int **need,int * resource) { int *CurrentAvailable; int *ProcessSet; int i; int j; int k; int *tmp_CurrentAvailable; int *tmp_ProcessSet; CurrentAvailable = (int *)malloc(sizeof(int) * source_count); ProcessSet = (int *)malloc(sizeof(int) * process_count); tmp_CurrentAvailable = (int *)malloc(sizeof(int) * source_count); tmp_ProcessSet = (int *)malloc(sizeof(int) * process_count); for(i = 0; i < process_count; i++)//已完成进程不参与模拟分配 { //判断是否完成 if(FINISH == done(source_count,i,need)) { ProcessSet[i] = OUT; } else { ProcessSet[i] = IN; } } for(j = 0; j < source_count; j++)//初始化资源 { CurrentAvailable[j] = resource[j]; } //拷贝 for(i = 0; i < process_count; i++) { tmp_ProcessSet[i] = ProcessSet[i]; } for(j = 0; j < source_count; j++) { tmp_CurrentAvailable[j] = CurrentAvailable[j]; } while(1) { j = 0; while(j < process_count) { if(IN == ProcessSet[j])//找是否有可分配的 { for(k = 0; k < source_count; k++)//每个资源是否符合 { if(need[j][k] > CurrentAvailable[k]) { break; } } if(k == source_count)//符合 { ProcessSet[j] = OUT; for(k = 0; k < source_count; k++) { CurrentAvailable[k] += allocation[j][k]; } break; } } j++; } if(process_count == j)//没找到 { break; } } for(i = 0; i < process_count; i++) { if(IN == ProcessSet[i]) { free(CurrentAvailable); free(ProcessSet); free(tmp_CurrentAvailable); free(tmp_ProcessSet); return DANGER; } } free(CurrentAvailable); free(ProcessSet); printf("\n"); allocate_list(source_count,process_count,allocation,need,tmp_CurrentAvailable,tmp_ProcessSet,1);//打印所有可能的序列 free(tmp_CurrentAvailable); free(tmp_ProcessSet); return SAFE; }
ps: allocate_list();//打印所有可能的序列 该函数下次介绍
转载地址:https://blog.csdn.net/Insanity666/article/details/53931533 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!