Bankers algorithm

Banker's Algorithm

Banker's algorithm is a deadlock avoidance algorithm. It is named so because this algorithm is used in banking systems to determine whether a loan can be granted or not.

Consider there are n account holders in a bank and the sum of the money in all of their accounts is S. Everytime a loan has to be granted by the bank, it subtracts the loan amount from the total money the bank has. Then it checks if that difference is greater than S. It is done because, only then, the bank would have enough money even if all the n account holders draw all their money at once.

Banker's algorithm works in a similar way in computers. Whenever a new process is created, it must exactly specify the maximum instances of each resource type that it needs.

Let us assume that there are n processes and m resource types. Some data structures are used to implement the banker's algorithm. They are:

Need[i][j] = Max[i][j] - Allocation [i][j]
  • Available: It is an array of length m. It represents the number of available resources of each type. If Available[j] = k, then there are k instances available, of resource type Rj.
  • Max: It is an n x m matrix which represents the maximum number of instances of each resource that a process can request. If Max[i][j] = k, then the process Pi can request atmost k instances of resource type Rj.
  • Allocation: It is an n x m matrix which represents the number of resources of each type currently allocated to each process. If Allocation[i][j] = k, then process Pi is currently allocated k instances of resource type Rj.
  • Need: It is an n x m matrix which indicates the remaining resource needs of each process. If Need[i][j] = k, then process Pi may need k more instances of resource type Rj to complete its task.

Safety Algorithm:

  1. Let Work and Finish be vectors of length m and n, respectively. Initially,
    Work = Available
    Finish[i] =false for i = 0, 1, ... , n - 1.

    This means, initially, no process has finished and the number of available resources is represented by the Available array.

  2. Find an index i such that both
    Finish[i] ==false
    Needi <= Work

    If there is no such i present, then proceed to step 4.

    It means, we need to find an unfinished process whose need can be satisfied by the available resources. If no such process exists, just go to step 4.

  3. Perform the following:
    Work = Work + Allocation;
    Finish[i] = true;

    Go to step 2.

    When an unfinished process is found, then the resources are allocated and the process is marked finished. And then, the loop is repeated to check the same for all other processes.

  4. If Finish[i] == true for all i, then the system is in a safe state.

    That means if all processes are finished, then the system is in safe state.