admin 管理员组文章数量: 887021
一、银行家算法
银行家是用来检测进程是否会发送死锁的一种算法,这是死锁避免的一种提前预防的机制。可以利用银行家算法进行系统安全进行一个预估。下面我将用一个案例来详细介绍银行家算法的过程。
二、银行家算法
#include <stdio.h>
int main(){
int b = 0;
int count = 0, m, n, process, temp, resource;
int allocation_table[5] = {0, 0, 0, 0, 0};
int available[5], current[5][5], maximum_claim[5][5];
int maximum_resources[5], running[5], safe_state = 0;
printf("\n输入总共的进程数:\t");
scanf("%d", &process);
for(m = 0; m < process; m++) {
running[m] = 1;
count++;
}
printf("\n输入要分配的资源总数:\t");
scanf("%d", &resource);
printf("\n输入需要个数:\t");
for(m = 0; m < resource; m++) {
scanf("%d", &maximum_resources[m]);
}
printf("\n输入分配资源表:\n");
for(m = 0; m < process; m++) {
for(n = 0; n < resource; n++)
{
scanf("%d", ¤t[m][n]);
}
}
printf("\n输入最大需求表:\n");
for(m = 0; m < process; m++) {
for(n = 0; n < resource; n++)
{
scanf("%d", &maximum_claim[m][n]);
}
}
printf("\n线程载体 \n");
for(m = 0; m < resource; m++) {
printf("\t%d ", maximum_resources[m]);
}
printf("\n 分配资源表\n");
for(m = 0; m < process; m++) {
for(n = 0; n < resource; n++) {
printf("\t%d", current[m][n]);
}
printf("\n");
}
printf("\n最大需求表 \n");
for(m = 0; m < process; m++) {
for(n = 0; n < resource; n++) {
printf("\t%d", maximum_claim[m][n]);
}
printf("\n");
}
for(m = 0; m < process; m++) {
for(n = 0; n < resource; n++) {
allocation_table[n] = allocation_table[n] + current[m][n];
}
}
printf("\n已经分配的资源 \n");
for(m = 0; m < resource; m++) {
printf("\t%d", allocation_table[m]);
}
for(m = 0; m < resource; m++) {
available[m] = maximum_resources[m] - allocation_table[m];
}
printf("\n剩余资源:");
for(m = 0; m < resource; m++) {
printf("\t%d", available[m]);
}
printf("\n");
while(count != 0) {
safe_state = 0;
for(m = 0; m < process; m++) {
if(running[m]) {
temp = 1;
for(n = 0; n < resource; n++) {
if(maximum_claim[m][n] - current[m][n] > available[n]) {
temp = 0;
break;
}
}
if(temp) {
printf("\n进程 %d 正在执行中 \n", m + 1);
running[m] = 0;
count--;
safe_state = 1;
for(n = 0; n < resource; n++) {
available[n] = available[n] + current[m][n];
}
break;
}
}
}
if(!safe_state) {
printf("\n进程处于非安全状态 \n");
break;
}
else {
printf("\n进程处于安全状态 \n");
printf("\n可用资源\n");
for(m = 0; m < resource; m++)
{
printf("\t%d", available[m]);
}
printf("\n");
}
}
return 0;
}
版权声明:本文标题:操作系统之死锁检测算法:银行家算法 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1715796355h651680.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论