银行家算法

#include<stdio.h>
#include<stdlib.h>
static int available[3]={3,3,2};
static int allocation[5][3]={{0,1,0},{2,0,0},{3,0,2},{2,1,1,},{0,0,2}};
static int need[5][3]={{7,4,3},{1,2,2},{6,0,0},{0,1,1},{4,3,1}};
int work[3], finish[4],state;

int safe()
{
  int i,j=0;
  for(i=0;i<4;i++)
    if(finish[i]==1)
    j++;
    if(j==4)    
    return 1;
    return 0;
}

void show()
{
  if(safe())
  {
    state=1;
    printf("system is in safe state/n");
  }
  else
  {
    state=0;
    printf("system is not in safe state/n");
   }
}

void reallocation(int k)
{
  int j,i=k;
  for(j=0;j<3;j++)
  work[j]+=allocation[i][j];
  finish[i]=1;
}

int check(int k)
{
  int j,i=k,l=0;
  if(finish[i]==0)
  {
    for(j=0;j<3;j++)
    if(need[i][j]<=work[j])
    l++;
   }
    if(l==3)
      return 1;
      return 0;
}

int find()
{
  int i,j=0;
  for(i=0;i<4;i++)
  {
    if(check(i))
      break;
      else
      j++;
  }
  if(j==4)
    return -1;
    return i;
}

void  safestatecheck()
{
  while(!safe())
  {
    if(find()!=-1)
      reallocation(find());
      else
      break;
   } 
  show();
}

main()
{
  int i,id,k=0,request[5][3];
  for(i=0;i<3;i++)
    work[i]=available[i];
  for(i=0;i<4;i++)
    finish[i]=0;
    safestatecheck();
    while(1)
    {     
      printf("switch the id of process,please/n");
      scanf("%d",&id);
      if(id<5) 
        break;
      else printf("error,");
    }
  for(i=0;i<3;i++)
   {
     printf("input the number of resourse%d/n",i);
     scanf("%d",&request[id][i]);
   }
  for(i=0;i<3;i++)
    if(request[id][i]<=need[id][i])
      k++;
      if(k<3)
    {
      printf("system can't accept the request/n");
      exit(1);
    }
    else
    {             k=0;
      for(i=0;i<3;i++)
      if(request[id][i]<=available[i])
      k++;
      if(k<3)
      {
         printf("process must wait/n");
         exit(1);
      }
      else
      {
         for(i=0;i<3;i++)
         {
            available[i]-=request[id][i];
            allocation[id][i]+=request[id][i];
            need[id][i]-=request[id][i];
         }
      }
  }
   for(i=0;i<3;i++)
     work[i]=available[i];       
   for(i=0;i<4;i++)
     finish[i]=0;
     safestatecheck();
     if(!state)
     {
       printf("process must wait /n");
       for(i=0;i<3;i++)
       {
          available[i]+=request[id][i];
          allocation[id][i]-=request[id][i];
          need[id][i]+=request[id][i];
       }
     }
   else
     printf("the allocation of the resourses is success/n");
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值