Shailrshah

Banker's algorithm

Sep 15th, 2014
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. #include <stdio.h>
  2. #define P 5
  3. #define R 4
  4.  
  5. int main(){
  6.     int allocated[P][R] = {{1,2,1,1},{1,2,1,1},{1,2,0,1},{2,2,1,1},{1,1,1,1}};;
  7.     int needed[P][R] = {{1,2,0,2},{1,2,2,3},{1,1,0,0},{2,2,0,1},{2,2,1,2}};
  8.     int done[P] = {0, 0, 0, 0, 0};
  9.     int available[R] = {2, 1, 0, 0};
  10.     int completed = 0, count, i, j; //i represents process, j represents resource
  11.     while(1){
  12.         for(i = 0; i < P; i++){
  13.             if(done[i])continue;
  14.             count = 0;
  15.             for(j = 0; j < R; j++)
  16.                 if(available[j] >= needed[i][j]) count++;
  17.                 else break;
  18.  
  19.             if(count == R){
  20.                 printf("%d is executing.\n", i+1);
  21.                 done[i] = 1;
  22.                 printf("The free array is:-\n");
  23.                 for(j = 0; j < R; j++){
  24.                     available[j] += allocated[i][j];
  25.                     needed[i][j] = 0;
  26.                     allocated[i][j] = 0;
  27.                     printf("%d ", available[j]);
  28.                 }
  29.                 printf("\n\n");
  30.                 break;
  31.             }
  32.         }
  33.         if(count != R){
  34.             printf("Unsafe!");
  35.             break;
  36.         }
  37.  
  38.         count=0;
  39.         for(i=0; i < P; i++)
  40.             if(done[i] == 1) count++;
  41.         if(count==P) return 0;
  42.     }
  43. }
Add Comment
Please, Sign In to add comment