
Introduction
Deadlock is when processes wait for each other to complete their execution. It is a possibility that one process holds some resources for making their execution, but another process holds the same resources, then this condition is known as deadlock.
In an operating system, deadlock can occur when multiple processes are trying to access some particular mutually exclusive resources.
For this reason, we need to calculate how many resources should be available to ensure that deadlock won't occur.
Let's understand this condition with the help of an example:
We are given the P number of processes in memory and the N number of resources each process needs to complete its execution. The task is to determine the number of resources R that will never result in a deadlock.
A system is in a deadlock-free condition if it satisfies the given condition, i.e.,
If Request for resources(R) <= Available Resources for a process.
Also see, Deadlock Detection and Recovery, Multiprogramming vs Multitasking
Algorithm for calculating the minimum number of resources
Condition for deadlock is: R ≥ P(N−1)+1
where,
R: The number of resources available.
P: The be the number of processes
N: The maximum number of resources needed by a process.
1. Create a function in which we will calculate the minimum number of resources.
static int no_resources(int P, int N)
num_of_resources = P * (N - 1) + 1;
return num_of_resources;
2. Inside the main function
Provide the number of processes and the resources needed for each process, and call the function to calculate the resources
int P = sc.nextInt();
int N = sc.nextInt();
System.out.print(no_resources(P, N));
Also Read About, FCFS Scheduling Algorithm and Open Source Operating System.
Program for deadlock-free condition(Java)
A system has R identical resources, P number of processes completed for them, and N is the maximum need of the resources for each of the processes. The task is to find the minimum number of Resources required so that deadlock never occurs.
import java.util.Scanner;
public class deadlocks {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number processes: ");
int P = sc.nextInt(); //Getting Number of processes
System.out.print("Enter max number of resources needed for each process: ");
int N = sc.nextInt(); //Getting max number of Resources needed for each process
System.out.print("number of resources required: ");
System.out.print(no_resources(P, N));
}
//CREATING A FUNCTION TO CALCULATE THE MINIMUM NO OF RESOURCES
static int no_resources(int P, int N) {
int num_of_resources = 0;
// Required condition so that there will be no deadlock is
// R >= P * (N - 1) + 1
num_of_resources = P * (N - 1) + 1;
return num_of_resources;
}
}
Output:
Enter number processes: 8
Enter max number of resources needed for each process: 3
number of resources required: 17




