Banker's Algorithm in Operating System
Banker's Algorithm in Operating System
Submitted by
Submitted To:
Mam Arshia
2
Max
It is a 2-d array of size ‘n*m’ that defines the maximum demand of each process in a
system.
Max [ i, j ] = k means process Pi may request at most ‘k’ instances of resource type Rj.
Allocation
It is a 2-d array of size ‘n*m’ that defines the number of resources of each type
currently allocated to each process.
Allocation [ i, j ] = k means process Pi is currently allocated ‘k’ instances of resource
type Rj
Need
It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of each
process.
Need [ i, j ] = k means process Pi currently need ‘k’ instances of resource type Rj
Need [ i, j ] = Max [ i, j ] – Allocation [ i, j ]
Allocationi specifies the resources currently allocated to process Pi and Needi specifies the
additional resources that process Pi may still request to complete its task.
Banker’s algorithm consists of Safety algorithm and Resource request algorithm.
Safety Algorithm
3
The algorithm for finding out whether or not a system is in a safe state can be described as
follows:
Let Work and Finish be vectors of length ‘m’ and ‘n’ respectively.
Initialize: Work = Available
Finish[i] = false; for i=1, 2, 3, 4….n
Find an i such that both
Finish[i] = false
Needi <= Work
if no such i exists goto step (4)
Work = Work + Allocation[i]
Finish[i] = true
goto step (2)
if Finish [i] = true for all i
then the system is in a safe state
Example:
Considering a system with five processes P0 through P4 and three resources of type A, B, C.
Resource type A has 10 instances, B has 5 instances and type C has 7 instances. Suppose at
time t0 following snapshot of the system has been taken:
What will happen if process P1 requests one additional instance of resource type A and two
instances of resource type C?
5
We must determine whether this new system state is safe. To do so, we again execute Safety
algorithm on the above data structures.
Banker's Algorithm
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4
int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}
if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
7
break;
}
}
if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}
return (0);