避免死鎖的銀行家算法


死鎖的定義>

   如果一組進程中的每一個進程都在等待僅由該組進程中的其他進程才能引發的事件,那仫該組進程就是死鎖的.

產生死鎖的必要條件>

    1).互斥條件:進程對所分配到的資源進行排它性使用,即在一段時間內,某資源只能被一個進程占用。如果此時還有其他進程請求該資源,則請求資源只能等待,直至占有該資源的進程用畢釋放.

    2).請求和保持條件:進程已經保持了至少一個資源,但又提出了新的資源請求,而該資源已經被其他進程占有,此時請求進程被保持,但對自己所獲得的資源又保持不放.

    3).不可搶占條件:進程已獲得的資源在未使用完之前不可被搶占,只能在使用完成后自己釋放.

    4).環路等待:在發生死鎖時,必然存在一個進程,資源的循環鏈.

   

 死鎖產生的原因>

   1).競爭可重用不可搶占式的資源

   2).競爭可消耗資源

   3).進程推進順序不當.

   可重用性資源:可供重復使用多次的資源.

   不可搶占性資源:一旦系統把某資源分配給該進程后,就不能將它強行收回,只能在進程使用完后自動釋放.

   可消耗資源:又叫臨時性資源,它是在進程運行期間,由進程動態的創建和消耗的.

 利用銀行家算法解決死鎖>

 

1).銀行家算法中的數據結構

      (1).可利用資源向量Available

      (2).最大需求矩陣Max

      (3).分配矩陣Allocation

      (4).需求矩陣Need

2).銀行家算法

Request請求向量,

     (1).如果Request[i] <= Need[i][j]轉下步,否則它所需要的資源數已超過它所需要的最大值

     (2).如果Request[i] <= Available[i][j]轉下步,否則尚無足夠資源,進程需等待  

     (3).系統試分配給進程p,並修改Available,Allocation和Need

                   Available[j] -= Request[j]

                   Allocation[i][j] += Request[j]

                   Need[i][j] -= Request[j]

     (4)系統執行安全性算法,檢查此次資源分配后系統是否處於安全狀態.若安全,才正式分配;否則恢復原來的分配狀態,讓該進程等待

3).安全性算法

    (1).設置兩個向量,工作向量Work,在執行安全性算法開始時 Work=Available;Finish:表示有足夠的資源分配給進程,使之運行完成,Finish[i]=false;當有足夠資源分配給進程時,再另Finish[i]=false

   (2).從進程集合中找到一個滿足該條件的進程:

           Finish[i]=false

           Need[i][j] <= Work[j]

   (3).當進程獲得資源后,可順利執行,並修改Work向量和Finsh向量

          Work[i] += Allocation[i][j]

          Finish[i]=true

   (4).如果所有進程的Finish[i]=true說明系統處於安全狀態,否則系統處於不安全狀態.

   在實現這份代碼的時候陷入了一個誤區那就是當你找到了一個安全序列之后,它查找過的Finish必定會被修改為true,而Finish這個數組又是在全局定義的,所以只要找到一次正確的安全序列這個Finish所找到的位就會被置為true會一直出現找到安全序列的,所以在找到安全序列之后一定要將Finish重新賦初值false,這個問題讓我排錯了半天,在定義變量的時候最好不要定義為全局的。。。

    

  1. const int MAXPROCESS=100;  
  2. const int MAXRESOURCE=100;   
  3.   
  4. int Available[MAXRESOURCE];         //可用資源向量    
  5. int Max[MAXPROCESS][MAXRESOURCE];   //最大需求矩陣    
  6. int Allocation[MAXPROCESS][MAXRESOURCE];  //分配矩陣    
  7. int Need[MAXPROCESS][MAXRESOURCE];        //需求矩陣    
  8.   
  9. int Request[MAXRESOURCE];      //請求向量    
  10.    
  11. int Work[MAXRESOURCE];         //工作向量    
  12. bool Finish[MAXPROCESS];   
  13. int SafeSeries[MAXPROCESS];    //安全序列    
  14.   
  15. int n;   //進程數    
  16. int m;   //資源數    
  17.   
  18. void Init()    
  19. {    
  20.     cout<<"請輸入進程總數>";    
  21.     cin>>n;  
  22.     cout<<"請輸入資源種類數>";    
  23.     cin>>m;  
  24.     int i,j;    
  25.     printf("請輸入%d類資源的當前可利用資源數目>\n",m);  
  26.     for( i = 0; i < m; ++i )    
  27.     {    
  28.         cin >> Available[i];    
  29.     }    
  30.     printf("最大需求矩陣(%d*%d輸入)>\n",n,m);  
  31.     for( i = 0; i < n; ++i )    
  32.     {    
  33.         for( j = 0; j < m; ++j )    
  34.         {    
  35.             cin >> Max[i][j];    
  36.         }    
  37.     }    
  38.     printf("分配矩陣(%d*%d輸入)>\n",n,m);   
  39.     for( i = 0; i < n; ++i )    
  40.     {    
  41.         for( j = 0; j < m; ++j )    
  42.         {    
  43.             cin >> Allocation[i][j];    
  44.         }    
  45.     }    
  46.     printf("需求矩陣(%d*%d輸入)\n",n,m);   
  47.     for( i = 0; i < n; ++i )    
  48.     {    
  49.         for( j = 0; j < m; ++j )    
  50.         {    
  51.             cin >> Need[i][j];    
  52.         }    
  53.     }    
  54. }    
  55.   
  56. bool IsSafe()    
  57. {    
  58.     int i=0;  
  59.     for (i=0;i<n;++i)  
  60.     {  
  61.         if(Finish[i] == true)  
  62.             continue;  
  63.         else  
  64.             break;  
  65.     }  
  66.     if(i == n)  
  67.         return true;    //安全  
  68.     else  
  69.         return false;   //不安全  
  70. }     
  71.   
  72. bool Select(int &tmp,int tmpNeed[][MAXRESOURCE])    
  73. {    
  74.     //選擇一個Finish[i]=false,Need[i]<=Work[i]   
  75.     int j=0;   
  76.     for (int i=0;i<n;++i)  
  77.     {  
  78.         if(Finish[i])  
  79.             continue;  
  80.         for (j=0;j<m;++j)  
  81.         {  
  82.             if(tmpNeed[i][j] > Work[j])  
  83.                 break;  
  84.         }  
  85.         if(j == m)  
  86.         {  
  87.             tmp=i;  
  88.             return true;  
  89.         }  
  90.     }  
  91.     return false;  
  92. }    
  93.   
  94. bool Safe(int *tmpAvail,int tmpAlloc[][MAXRESOURCE],int tmpNeed[][MAXRESOURCE])    
  95. {    
  96.     for(int i = 0; i < n; ++i)    
  97.     {    
  98.         Finish[i] = false;    
  99.     }    
  100.     for (int j = 0; j < m; ++j)    
  101.     {    
  102.         Work[j] = tmpAvail[j];    
  103.     }    
  104.     int tmp=0;    
  105.     int index = 0;    
  106.     while(Select(tmp,tmpNeed))    
  107.     {    
  108.         Finish[tmp] = true;    
  109.         for (int k = 0; k < m; ++k)    
  110.         {    
  111.             Work[k] += tmpAlloc[tmp][k];    
  112.         }    
  113.         SafeSeries[index++] = tmp;  
  114.     }    
  115.     if(IsSafe())    
  116.         return true;    //安全  
  117.     else  
  118.         return false;   //不安全  
  119. }     
  120.   
  121. void Display()  
  122. {  
  123.     int i=0;  
  124.     int j=0;  
  125.     cout<<"當前可利用的資源數目"<<endl;  
  126.     for(i = 0; i < m; ++i)    
  127.     {    
  128.         cout << Available[i]<<" ";    
  129.     }    
  130.     cout<<endl;  
  131.     cout<<"最大需求矩陣"<<endl;  
  132.     for(i = 0; i < n; ++i )    
  133.     {    
  134.         for( j = 0; j < m; ++j)    
  135.         {    
  136.             cout<<Max[i][j]<<" ";  
  137.         }    
  138.         cout<<endl;  
  139.     }    
  140.     cout<<"分配矩陣"<<endl;  
  141.     for( i = 0; i < n; ++i )    
  142.     {    
  143.         for( j = 0; j < m; ++j )    
  144.         {    
  145.             cout<<Allocation[i][j]<<" ";   
  146.         }    
  147.         cout<<endl;  
  148.     }    
  149.     cout<<"需求矩陣"<<endl;  
  150.     for( i = 0; i < n; ++i )    
  151.     {    
  152.         for( j = 0; j < m; ++j )    
  153.         {    
  154.             cout<<Need[i][j]<<" ";  
  155.         }    
  156.         cout<<endl;  
  157.     }   
  158. }  
  159.   
  160. void BankA()  
  161. {  
  162.     int i=0;  
  163.     int index=0;  
  164.     cout<<"請輸入請求資源的進程下標>";  
  165.     cin>>index;  
  166.     assert(index < n && index >= 0);  
  167.     cout<<"請輸入當前的請求資源>"<<endl;  
  168.     for (i=0;i<m;++i)  
  169.     {  
  170.         cin>>Request[i];  
  171.     }  
  172.     for (i=0;i<m;++i)  
  173.     {  
  174.         if(Request[i] <= Need[index][i])  
  175.         {  
  176.             continue;  
  177.         }  
  178.         else  
  179.         {  
  180.             cout<<"第一次試分配失敗"<<endl;  
  181.             break;  
  182.         }  
  183.     }  
  184.     if(i < 3)   //如果第一次試分配失敗則不執行后面的語句  
  185.     {  
  186.         return ;  
  187.     }  
  188.     for(i=0;i<m;++i)  
  189.     {  
  190.         if(Request[i] <= Available[i])  
  191.         {  
  192.             continue;  
  193.         }  
  194.         else  
  195.         {  
  196.             cout<<"第二次試分配失敗"<<endl;  
  197.             break;  
  198.         }  
  199.     }  
  200.     if(i < 3)     //如果第二次試分配失敗則不同執行后面的語句  
  201.     {  
  202.         return ;  
  203.     }  
  204.     //開始試分配  
  205.     int tmpAvail[MAXRESOURCE]={0};  
  206.     int tmpAlloc[MAXPROCESS][MAXRESOURCE]={0};  
  207.     int tmpNeed[MAXPROCESS][MAXRESOURCE]={0};  
  208.     memmove(tmpAvail,Available,sizeof(int)*MAXRESOURCE);  
  209.     memmove(tmpAlloc,Allocation,sizeof(int)*MAXPROCESS*MAXRESOURCE);  
  210.     memmove(tmpNeed,Need,sizeof(int)*MAXPROCESS*MAXRESOURCE);  
  211.     for (int i=0;i<m;++i)  
  212.     {  
  213.         tmpAvail[i] -= Request[i];  
  214.         tmpAlloc[index][i] += Request[i];  
  215.         tmpNeed[index][i] -= Request[i];  
  216.     }  
  217.     //開始執行安全性算法  
  218.     bool ret=Safe(tmpAvail,tmpAlloc,tmpNeed);  
  219.     if(ret == true)  
  220.     {  
  221.         //如果試分配成功則更新Available,Allocation,Allocation的狀態  
  222.         memmove(Available,tmpAvail,sizeof(int)*MAXRESOURCE);  
  223.         memmove(Allocation,tmpAlloc,sizeof(int)*MAXPROCESS*MAXRESOURCE);  
  224.         memmove(Need,tmpNeed,sizeof(int)*MAXPROCESS*MAXRESOURCE);  
  225.         cout<<"進程p"<<index<<"請求資源允許"<<endl;  
  226.     }  
  227.     else  
  228.     {  
  229.         //只要試分配失敗則將Finish置為false  
  230.         for(int i = 0; i < n; ++i)    
  231.         {    
  232.             Finish[i] = false;    
  233.         }    
  234.         cout<<"第三次試分配失敗"<<endl;  
  235.     }  
  236. }  
  237.   
  238. void Menu()  
  239. {  
  240.     cout<<"*************銀行家算法*************"<<endl;  
  241.     cout<<"**********1.測試安全性代碼**********"<<endl;  
  242.     cout<<"**********2.測試銀行家算法**********"<<endl;  
  243.     cout<<"**********3.初始化******************"<<endl;  
  244.     cout<<"**********4.打印矩陣****************"<<endl;  
  245.     cout<<"**********0.退出********************"<<endl;  
  246. }  

 

   test.cpp

   

  1. void testBank()  
  2. {  
  3.     int index=0;  
  4.     int flag=1;  
  5.     while (flag)  
  6.     {  
  7.         Menu();  
  8.         cout<<"請輸入您的選擇"<<endl;  
  9.         cin>>index;  
  10.         switch(index)  
  11.         {  
  12.         case 1:  
  13.             Safe(Available,Allocation,Need);  
  14.             if(IsSafe())    
  15.             {    
  16.                 cout<<"該時刻是安全的,安全序列為>";   
  17.                 for (int i = 0; i < n ; ++i)    
  18.                 {    
  19.                     printf("p%d->",SafeSeries[i]);  
  20.                 }    
  21.                 cout<<"end"<<endl;  
  22.                 //分配成功將Finish的值置為false  
  23.                 for(int i = 0; i < n; ++i)    
  24.                 {    
  25.                     Finish[i] = false;    
  26.                 }    
  27.             }    
  28.             else    
  29.             {    
  30.                 cout<<"該時刻是不安全的"<<endl;  
  31.             }   
  32.             break;  
  33.         case 2:  
  34.             BankA();  
  35.             if(IsSafe())    
  36.             {    
  37.                 cout<<"安全序列為>";   
  38.                 for (int i = 0; i < n ; ++i)    
  39.                 {    
  40.                     printf("p%d->",SafeSeries[i]);  
  41.                 }    
  42.                 cout<<"end"<<endl;  
  43.                 //分配成功將Finish的值置為false  
  44.                 for(int i = 0; i < n; ++i)    
  45.                 {    
  46.                     Finish[i] = false;    
  47.                 }    
  48.             }    
  49.             else    
  50.             {    
  51.                 cout<<"進程請求資源不被允許"<<endl;  
  52.             }   
  53.             break;  
  54.         case 3:  
  55.             Init();  
  56.             break;  
  57.         case 4:  
  58.             Display();  
  59.             break;  
  60.         case 0:  
  61.             flag=0;  
  62.             break;  
  63.         default:  
  64.             cout<<"您的輸入錯誤,請重新輸入"<<endl;  
  65.             break;  
  66.         }  
  67.     }  
  68. }  

  
 

 

  雖然搞了一下午寫完整了這個銀行家算法,整體效果還算滿意,但是作為網絡工程專業的學生今年雖然學了java的GUI但是仍然不會用圖形用戶界面(GUI)來對這個程序做一個界面出來,感覺好悲催哭,以后一定努力學習這方面的知識

  實現效果

   

     

     

    

    

    

下面是java代碼實現
 
[java] view plain copy
  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 : 4  
  82. Enter allocation matrix -->  
  83. 1  
  84. 3  
  85. 0  
  86. Enter max matrix -->  
  87. 2  
  88. 4  
  89. 0  
  90. Enter available matrix -->  
  91. 2  
  92. Allocated process : 0  
  93. Allocated process : 1  
  94. Allocated process : 2  
  95. Safely allocated 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM