Lab6 Deadlock
Lab6 Deadlock
| Lab 6
The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests
for safety by simulating the allocation for predetermined maximum possible amounts of all
resources, then makes an “s-state” check to test for possible activities, before deciding
whether allocation should be allowed to continue.
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:
Page | 1
4thLevel | Operating System. | Lab 6
Question2. Is the system in a safe state? If Yes, then what is the safe sequence?
Applying the Safety algorithm on the given system,
Question3. What will happen if process P1 requests one additional instance of resource
type A and two instances of resource type C?
We must determine whether this new system state is safe. To do so, we again execute
Safety algorithm on the above data structures………complete.
Page | 2
4thLevel | Operating System. | Lab 6
Banker's Algorithm Implementation:
class GFG
{
static int n = 5; // Number of processes
static int m = 3; // Number of resources
int[,] need = new int[n, m];
int[,] max;
int[,] alloc;
int[] avail;
int[] safeSequence = new int[n];
void initializeValues()
{
// P0, P1, P2, P3, P4 are the Process
// names here Allocation Matrix
alloc = new int[,] {{ 0, 1, 0 }, //P0
{ 2, 0, 0 }, //P1
{ 3, 0, 2 }, //P2
{ 2, 1, 1 }, //P3
{ 0, 0, 2 }};//P4
// MAX Matrix
max = new int[,] {{ 7, 5, 3 }, //P0
{ 3, 2, 2 }, //P1
{ 9, 0, 2 }, //P2
{ 2, 2, 2 }, //P3
{ 4, 3, 3 }};//P4
// Available Resources
avail = new int[] { 3, 3, 2 };
}
void isSafe()
{
int count = 0;
Page | 3
4thLevel | Operating System. | Lab 6
Boolean flag = false;
for (int i = 0; i < n; i++)
{
if (visited[i] == false)
{
int j;
for (j = 0; j < m; j++)
{
if (need[i, j] > work[j])
break;
}
if (j == m)
{
safeSequence[count++] = i;
visited[i] = true;
flag = true;
for (j = 0; j < m; j++)
{
work[j] = work[j] + alloc[i, j];
}
}
}
}
if (flag == false)
{
break;
}
}
if (count < n)
{
Console.WriteLine("The System is UnSafe!");
}
else
{
//System.out.println("The given System is Safe");
Console.WriteLine("Following is the SAFE Sequence");
for (int i = 0; i < n; i++)
{
Console.Write("P" + safeSequence[i]);
if (i != n - 1)
Console.Write(" -> ");
}
}
}
void calculateNeed()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
need[i, j] = max[i, j] - alloc[i, j];
}
}
}
// Driver Code
public static void Main(String[] args)
{
GFG gfg = new GFG();
Page | 4
4thLevel | Operating System. | Lab 6
gfg.initializeValues();
Output:
*******************************
Page | 5