避免死锁之银行家算法

上篇博客中 进程管理之死锁 我们讲到了进程管理中死锁的各种问题,其中留下了死锁避免算法中著名的银行家算法没讲,下面就为大家详细解读。

1.安全序列

讲银行家算法之前,我们首先引入安全序列的定义:所谓系统是安全的,是指系统中的所有进程能够按照某一种次序分配资源,并且依次地运行完毕,这种进程序列{P1,P2,...,Pn}就是安全序列。如果存在这样一个安全序列,则系统是安全的;如果系统不存在这样一个安全序列,则系统是不安全的。
安全序列{P1,P2,...,Pn}是这样组成的:若对于每一个进程Pi,它需要的附加资源可以被系统中当前可用资源加上所有进程Pj当前占有资源之和所满足,则{P1,P2,...,Pn}为一个安全序列,这时系统处于安全状态,不会进入死锁状态。  
虽然存在安全序列时一定不会有死锁发生,但是系统进入不安全状态(四个死锁的必要条件同时发生)也未必会产生死锁。当然,产生死锁后,系统一定处于不安全状态。 

2.银行家算法

(为了熟悉英语请原谅我借用wiki上的文字来描述)
For the Banker's algorithm to work, it needs to know three things:
  • How much of each resource each process could possibly request[CLAIMS]
  • How much of each resource each process is currently holding[ALLOCATED]
  • How much of each resource the system currently has available[AVAILABLE]
Resources may be allocated to a process only if it satisfies the following conditions:
  • request ≤ max, else set error condition as process has crossed maximum claim made by it.
  • request ≤ available, else process waits until resources are available.

Basic data structures to be maintained to implement the Banker's Algorithm:

  • Available: A vector of length m indicates the number of available resources of each type. If Available[j] = k, there are k instances of resource type Rj available.
  • Max: An n×m matrix defines the maximum demand of each process. If Max[i,j] = k, then Pi may request at most k instances of resource type Rj.
  • Allocation: An n×m matrix defines the number of resources of each type currently allocated to each process. If Allocation[i,j] = k, then process Pi is currently allocated k instance of resource type Rj.
  • Need: An n×m matrix indicates the remaining resource need of each process. If Need[i,j] = k, then Pi may need k more instances of resource type Rj to complete task.
Note: Need[i,j] = Max[i,j] - Allocation[i,j].


  • 银行家算法:
设进程i提出请求Request[j],则银行家算法按如下规则进行判断。
(1) 如果Request[j]≤Need[i,j],则转向(2),否则认为出错。

(2) 如果Request[j]≤Available[j],则转向(3);否则表示尚无足够资源,Pi需等待。

(3) 假设进程i的申请已获批准,于是修改系统状态:
Available[j]=Available[j]-Request[i]
Allocation[i,j]=Allocation[i,j]+Request[j]
Need[i,j]=Need[i,j]-Request[j]

(4)系统执行安全性检查,如安全,则分配成立;否则试探险性分配作废,系统恢复原状,进程等待。
  • 安全性检查
(1) 设置两个工作向量Work=Available;Finish[i]=False

(2) 从进程集合中找到一个满足下述条件的进程,
      Finish [i]=False;
      Need[i,j]≤Work[j];
     如找到,执行(3);否则,执行(4)

(3) 设进程获得资源,可顺利执行,直至完成,从而释放资源。
     Work[j]=Work[i]+Allocation[i,j];
Finish[i]=True;
go to step 2;

(4) 如所有的进程Finish[i]=true,则表示安全;否则系统不安全。


由于时间不早了就借用下wiki上的c语言实现代码,改天用java实现一遍。
  1. /*PROGRAM TO IMPLEMENT BANKER'S ALGORITHM 
  2.   *   --------------------------------------------*/  
  3. #include <stdio.h>  
  4. int curr[5][5], maxclaim[5][5], avl[5];  
  5. int alloc[5] = {0,0,0,0,0};  
  6. int maxres[5], running[5], safe=0;  
  7. int count = 0, i, j, exec, r, p,k=1;  
  8.    
  9. int main()  
  10. {  
  11.     printf("\nEnter the number of processes: ");  
  12.     scanf("%d",&p);  
  13.    
  14.     for(i=0;i<p;i++)  
  15.     {  
  16.         running[i]=1;  
  17.         count++;  
  18.     }  
  19.    
  20.     printf("\nEnter the number of resources: ");  
  21.     scanf("%d",&r);  
  22.    
  23.     for(i=0;i<r;i++)  
  24.     {   
  25.         printf("\nEnter the resource for instance %d: ",k++);  
  26.         scanf("%d",&maxres[i]);  
  27.     }  
  28.    
  29.     printf("\nEnter maximum resource table:\n");  
  30.     for(i=0;i<p;i++)  
  31.     {  
  32.         for(j=0;j<r;j++)  
  33.         {  
  34.             scanf("%d",&maxclaim[i][j]);  
  35.         }  
  36.     }  
  37.    
  38.     printf("\nEnter allocated resource table:\n");  
  39.     for(i=0;i<p;i++)  
  40.     {  
  41.         for(j=0;j<r;j++)  
  42.         {  
  43.             scanf("%d",&curr[i][j]);  
  44.         }  
  45.     }  
  46.    
  47.     printf("\nThe resource of instances: ");  
  48.     for(i=0;i<r;i++)  
  49.     {  
  50.         printf("\t%d",maxres[i]);  
  51.     }  
  52.    
  53.     printf("\nThe allocated resource table:\n");  
  54.     for(i=0;i<p;i++)  
  55.     {  
  56.         for(j=0;j<r;j++)  
  57.         {  
  58.             printf("\t%d",curr[i][j]);  
  59.         }  
  60.    
  61.         printf("\n");  
  62.     }  
  63.    
  64.     printf("\nThe maximum resource table:\n");  
  65.     for(i=0;i<p;i++)  
  66.     {  
  67.         for(j=0;j<r;j++)  
  68.         {  
  69.             printf("\t%d",maxclaim[i][j]);  
  70.         }  
  71.    
  72.         printf("\n");  
  73.     }  
  74.    
  75.     for(i=0;i<p;i++)  
  76.     {  
  77.         for(j=0;j<r;j++)  
  78.         {  
  79.             alloc[j]+=curr[i][j];  
  80.         }  
  81.     }  
  82.    
  83.     printf("\nAllocated resources:");  
  84.     for(i=0;i<r;i++)  
  85.     {  
  86.         printf("\t%d",alloc[i]);  
  87.     }  
  88.    
  89.     for(i=0;i<r;i++)  
  90.     {  
  91.         avl[i]=maxres[i]-alloc[i];  
  92.     }  
  93.    
  94.     printf("\nAvailable resources:");  
  95.     for(i=0;i<r;i++)  
  96.     {  
  97.         printf("\t%d",avl[i]);  
  98.     }  
  99.     printf("\n");  
  100.    
  101.     //Main procedure goes below to check for unsafe state.  
  102.     while(count!=0)  
  103.     {  
  104.         safe=0;  
  105.         for(i=0;i<p;i++)  
  106.         {  
  107.             if(running[i])  
  108.             {  
  109.                 exec=1;  
  110.                 for(j=0;j<r;j++)  
  111.                 {  
  112.                     if(maxclaim[i][j] - curr[i][j] > avl[j]){  
  113.                         exec=0;  
  114.                         break;  
  115.                     }  
  116.                 }  
  117.                 if(exec)  
  118.                 {  
  119.                     printf("\nProcess%d is executing\n",i+1);  
  120.                     running[i]=0;  
  121.                     count--;  
  122.                     safe=1;  
  123.    
  124.                     for(j=0;j<r;j++) {  
  125.                         avl[j]+=curr[i][j];  
  126.                     }  
  127.    
  128.                     break;  
  129.                 }  
  130.             }  
  131.         }  
  132.         if(!safe)  
  133.         {  
  134.             printf("\nThe processes are in unsafe state.\n");  
  135.             break;  
  136.         }  
  137.         else  
  138.         {  
  139.             printf("\nThe process is in safe state");  
  140.             printf("\nSafe sequence is:");  
  141.    
  142.             for(i=0;i<r;i++)  
  143.             {  
  144.                 printf("\t%d",avl[i]);  
  145.             }  
  146.    
  147.             printf("\n");  
  148.         }  
  149.     }  
  150. }  
  151.    
  152.    
  153. /*SAMPLE  OUTPUT 
  154. ----------------- 
  155. Enter the number of resources:4 
  156.   
  157. Enter the number of processes:5 
  158.   
  159. Enter  Claim Vector:8 5 9 7 
  160.   
  161. Enter Allocated Resource Table: 
  162. 2 0 1 1 
  163. 0 1 2 1 
  164. 4 0 0 3 
  165. 0 2 1 0 
  166. 1 0 3 0 
  167.   
  168. Enter Maximum Claim table: 
  169. 3 2 1 4 
  170. 0 2 5 2 
  171. 5 1 0 5 
  172. 1 5 3 0 
  173. 3 0 3 3 
  174.   
  175. The Claim Vector is:    8   5   9   7 
  176. The Allocated Resource Table: 
  177.     2   0   1   1 
  178.     0   1   2   1 
  179.     4   0   0   3 
  180.     0   2   1   0 
  181.     1   0   3   0 
  182.   
  183. The  Maximum Claim Table: 
  184.     3   2   1   4 
  185.     0   2   5   2 
  186.     5   1   0   5 
  187.     1   5   3   0 
  188.     3   0   3   3 
  189.   
  190.  Allocated resources:   7   3   7   5 
  191.  Available resources:   1   2   2   2 
  192.   
  193. Process3 is executing 
  194.   
  195.  The process is in safe state 
  196.  Available vector:  5   2   2   5 
  197. Process1 is executing 
  198.   
  199.  The process is in safe state 
  200.  Available vector:  7   2   3   6 
  201. Process2 is executing 
  202.   
  203.  The process is in safe state 
  204.  Available vector:  7   3   5   7 
  205. Process4 is executing 
  206.   
  207.  The process is in safe state 
  208.  Available vector:  7   5   6   7 
  209. Process5 is executing 
  210.   
  211.  The process is in safe state 
  212.  Available vector:  8   5   9   7 
  213.   
  214.  ---------------------------------------------------------*/  



下面是java代码实现

[java]  view plain copy print ?
  1. import java.util.Scanner;  
  2.   
  3. public class Bankers{  
  4.     private int need[][],allocate[][],max[][],avail[][],np,nr;  
  5.       
  6.     private void input(){  
  7.      Scanner sc=new Scanner(System.in);  
  8.      System.out.print("Enter no. of processes and resources : ");  
  9.      np=sc.nextInt();  //no. of process  
  10.      nr=sc.nextInt();  //no. of resources  
  11.      need=new int[np][nr];  //initializing arrays  
  12.      max=new int[np][nr];  
  13.      allocate=new int[np][nr];  
  14.      avail=new int[1][nr];  
  15.        
  16.      System.out.println("Enter allocation matrix -->");  
  17.      for(int i=0;i<np;i++)  
  18.           for(int j=0;j<nr;j++)  
  19.          allocate[i][j]=sc.nextInt();  //allocation matrix  
  20.         
  21.      System.out.println("Enter max matrix -->");  
  22.      for(int i=0;i<np;i++)  
  23.           for(int j=0;j<nr;j++)  
  24.          max[i][j]=sc.nextInt();  //max matrix  
  25.         
  26.         System.out.println("Enter available matrix -->");  
  27.         for(int j=0;j<nr;j++)  
  28.          avail[0][j]=sc.nextInt();  //available matrix  
  29.           
  30.         sc.close();  
  31.     }  
  32.       
  33.     private int[][] calc_need(){  
  34.        for(int i=0;i<np;i++)  
  35.          for(int j=0;j<nr;j++)  //calculating need matrix  
  36.           need[i][j]=max[i][j]-allocate[i][j];  
  37.          
  38.        return need;  
  39.     }  
  40.    
  41.     private boolean check(int i){  
  42.        //checking if all resources for ith process can be allocated  
  43.        for(int j=0;j<nr;j++)   
  44.        if(avail[0][j]<need[i][j])  
  45.           return false;  
  46.      
  47.     return true;  
  48.     }  
  49.   
  50.     public void isSafe(){  
  51.        input();  
  52.        calc_need();  
  53.        boolean done[]=new boolean[np];  
  54.        int j=0;  
  55.   
  56.        while(j<np){  //until all process allocated  
  57.        boolean allocated=false;  
  58.        for(int i=0;i<np;i++)  
  59.         if(!done[i] && check(i)){  //trying to allocate  
  60.             for(int k=0;k<nr;k++)  
  61.             avail[0][k]=avail[0][k]-need[i][k]+max[i][k];  
  62.          System.out.println("Allocated process : "+i);  
  63.          allocated=done[i]=true;  
  64.                j++;  
  65.              }  
  66.           if(!allocated) break;  //if no allocation  
  67.        }  
  68.        if(j==np)  //if all processes are allocated  
  69.         System.out.println("\nSafely allocated");  
  70.        else  
  71.         System.out.println("All proceess cant be allocated safely");  
  72.     }  
  73.       
  74.     public static void main(String[] args) {  
  75.   new Bankers().isSafe();  
  76.     }  
  77. }  
  78. --------------------------------------------------------------------------------------------------------------------------  
  79. Output  
  80. --------------------------------------------------------------------------------------------------------------------------  
  81. Enter no. of processes and resources : 3 4  
  82. Enter allocation matrix -->  
  83. 1 2 2 1  
  84. 1 0 3 3  
  85. 1 2 1 0  
  86. Enter max matrix -->  
  87. 3 3 2 2  
  88. 1 1 3 4  
  89. 1 3 5 0  
  90. Enter available matrix -->  
  91. 3 1 1 2  
  92. Allocated process : 0  
  93. Allocated process : 1  
  94. Allocated process : 2  
  95. Safely allocated  


参考资料:http://en.wikipedia.org/wiki/Banker's_algorithm#Safe_and_Unsafe_States
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值