模拟银行家算法,用银行家算法实现资源分配。
Output() 输出某时刻的资源分配情况;
Bank() 银行家算法的步骤 1、2、3、及4调用安全性算法;
Security() 进行安全性检查;
Main() 各种数据结构的定义。
假设 有0-4 五个进程(假设系统的当前状态是安全的),三类资源 即:A、B、C
(以下各种数据均取自课本P97例子)
T0 时刻的资源分配表(各种资源的数量分别为:10、5、7)
| 进程 | Max A B C | Allocation A B C | Need A B C | Available A B C | 
| P0 | 7 5 3 | 0 1 0 | 7 4 3 | 3 3 2 | 
| P1 | 3 2 2 | 2 0 0 | 1 2 2 |  | 
| P2 | 9 0 2 | 3 0 2 | 6 0 0 |  | 
| P3 | 2 2 2 | 2 1 1 | 0 1 1 |  | 
| P4 | 4 3 3 | 0 0 2 | 4 3 1 |  | 
output(int arr[5][3])
{
 int i,j;
 printf("    A  B  C\n");
 for(i=0;i<5;i++)
 {
  printf("P%d",i);
  for(j=0;j<3;j++)
  { printf("  %d",arr[i][j]); }
  printf("\n");
 }
}
int Security(int avialable[3],int need[5][3],int allocation[5][3])
{
    int j,i;
    int work[3];
    int finish[5]={0,0,0,0,0};
    for(j=0;j<3;j++)
    work[j]=avialable[j];
    for(i=0;i<5;i++)
    {
 if(finish[i]==0)
 {
  for(j=0;j<3;j++)
            if(need[i][j]<=work[i]&need[i][j]<=work[i]&need[i][j]<=work[i])
        work[j]=work[j]+allocation[i][j];
  finish[j]=1;
 }
    }
    for(i=0;i<5;i++)
    {
 if(finish[i]==0)
   return 0;
 else return 1;
    }
} */
Bank(int i,int request[3],int need[5][3],int avialable[3],int allocation[5][3])
{
 int 
 int j;
 printf("The process id:  %d\n",i);
 printf("The Process Request:");
 for(j=0;j<3;j++)
    printf(" %d",request[j]);
 printf("\n");
 if(request[0]<=need[i][0]&request[1]<=need[i][1]&request[2]<=need[i][2])
 {
     if(request[0]<=avialable[0]&request[1]<=avialable[1]&request[2]<=avialable[2])
     {
  for(j=0;j<3;j++)
  {
   avialable[j]=avialable[j]-request[j];
   allocation[i][j]=allocation[i][j]+request[j];
   need[i][j]=need[i][j]-request[j];
  }
  printf("The source after request:\n");
  printf("   Allocation\n");
  output(allocation);
  printf("   Need\n");
  output(need);
  printf("The Avialable after request:");
  for(j=0;j<3;j++)
  printf("  %d",avialable[j]);
  printf("\n");
     }
     else printf("RequestError!");
 }
 else printf("RequestError!");
 /*Security(avialable,need,allocation);*/
}
main()
{
 int id,i;
 int Avialable[3]={3,3,2};
 int Max[5][3]={{7,5,3},{3,2,2},{9,0,2},{2,2,2},{4,3,3}};
 int Allocation[5][3]={{0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}};
 int Need[5][3]={{7,4,3},{1,2,2},{6,0,0},{0,1,1},{4,3,1}};
 int Request[3];    /*i Id of Process*/
 printf("   MAX\n");
 output(Max);
 printf("   Allocation\n");
 output(Allocation);
 printf("   Need\n");
 output(Need);
 printf("The Avialable before request:");
for(i=0;i<3;i++)
 printf("  %d",Avialable[i]);
 printf("\n");
 scanf("%d %d %d %d",&id,&Request[0],&Request[1],&Request[2]);
 Bank(id,Request,Need,Avialable,Allocation);
}