The Wayback Machine - https://web.archive.org/web/20240926133639/https://www.geeksforgeeks.org/deadlock-prevention/
Open In App

Deadlock Prevention And Avoidance

Last Updated : 26 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When two or more processes try to access the critical section at the same time and they fail to access simultaneously or stuck while accessing the critical section then this condition is known as Deadlock.

Deadlock prevention and avoidance are strategies used in computer systems to ensure that different processes can run smoothly without getting stuck waiting for each other forever. Think of it like a traffic system where cars (processes) need to move through intersections (resources) without getting into a gridlock. In this article, we are going to discuss deadlock prevention and avoidance strategies in detail.

Deadlock Characteristics

 The deadlock has the following characteristics:

  • Mutual Exclusion
  • Hold and Wait
  • No Preemption
  • Circular Wait

Deadlock Prevention

We can prevent a Deadlock by eliminating any of the above four conditions. 

Eliminate Mutual Exclusion: It is not possible to dis-satisfy the mutual exclusion because some resources, such as the tape drive and printer, are inherently non-shareable. 

Eliminate Hold and Wait: Allocate all required resources to the process before the start of its execution, this way hold and wait condition is eliminated but it will lead to low device utilization. for example, if a process requires a printer at a later time and we have allocated a printer before the start of its execution printer will remain blocked till it has completed its execution. The process will make a new request for resources after releasing the current set of resources. This solution may lead to starvation.
 

Hold and Wait

Eliminate No Preemption : Preempt resources from the process when resources are required by other high-priority processes. 

Eliminate Circular Wait : Each resource will be assigned a numerical number. A process can request the resources to increase/decrease. order of numbering. For Example, if the P1 process is allocated R5 resources, now next time if P1 asks for R4, R3 lesser than R5 such a request will not be granted, only a request for resources more than R5 will be granted. 

Detection and Recovery: Another approach to dealing with deadlocks is to detect and recover from them when they occur. This can involve killing one or more of the processes involved in the deadlock or releasing some of the resources they hold.

Deadlock Avoidance

A deadlock avoidance policy grants a resource request only if it can establish that granting the request cannot lead to a deadlock either immediately or in the future. The kernal lacks detailed knowledge about future behavior of processes, so it cannot accurately predict deadlocks.

To facilitate deadlock avoidance under these conditions, it uses the following conservative approach: Each process declares the maximum number of resource units of each class that it may require. The kernal permits a process to request these resource units in stages- i.e. a few resource units at a time- subject to the maximum number declared by it and uses a worst case analysis technique to check for the possibility of future deadlocks. A request is granted only if there is no possibility of deadlocks; otherwise, it remains pending until it can be granted. This approach is conservative because a process may complete its operation without requiring the maximum number of units declared by it.

Resource Allocation Graph

The resource allocation graph (RAG) is used to visualize the system’s current state as a graph. The Graph includes all processes, the resources that are assigned to them, as well as the resources that each Process requests. Sometimes, if there are fewer processes, we can quickly spot a deadlock in the system by looking at the graph rather than the tables we use in Banker’s algorithm. Deadlock avoidance can also be done with Banker’s Algorithm. 

Banker’s Algorithm

Bankers’s Algorithm is a resource allocation and deadlock avoidance algorithm which test all the request made by processes for resources, it checks for the safe state, and after granting a request system remains in the safe state it allows the request, and if there is no safe state it doesn’t allow the request made by the process. 

Inputs to Banker’s Algorithm

  • Max needs of resources by each process. 
  • Currently, allocated resources by each process. 
  • Max free available resources in the system.

The request will only be granted under the below condition

  • If the request made by the process is less than equal to the max needed for that process. 
  • If the request made by the process is less than equal to the freely available resource in the system.

Timeouts: To avoid deadlocks caused by indefinite waiting, a timeout mechanism can be used to limit the amount of time a process can wait for a resource. If the help is unavailable within the timeout period, the process can be forced to release its current resources and try again later.

Example: 

Total resources in system:
A B C D
6 5 7 6

The total number of resources are

Available system resources are:
A B C D
3 1 1 2

Available resources are 

Processes (currently allocated resources):
A B C D
P1 1 2 2 1
P2 1 0 3 3
P3 1 2 1 0

Maximum resources we have for a process

Processes (maximum resources):
A B C D
P1 3 3 2 2
P2 1 2 3 4
P3 1 3 5 0

Need = Maximum Resources Requirement – Currently Allocated Resources.

Need = maximum resources - currently allocated resources.
Processes (need resources):
A B C D
P1 2 1 0 1
P2 0 2 0 1
P3 0 1 4 0

Conclusion

Operating Systems employ deadlock avoidance to prevent deadlock by using the Banker’s algorithm or the resource allocation graph. Deadlock avoidance works by informing the operating system of the resources needed by the process to finish execution, and the operating system then determines whether or not the requirements can be met.

The System is said to be in a Safe state if all the resources required by the Process are satisfied with the resources that are currently available. The System is said to be in an unsafe state if all of the resource requirements of the Process cannot be met by the available resources in any way. Deadlock prevention is more strict than Deadlock Avoidance. 

Frequently Asked Questions on Deadlock Prevention And Avoidance – FAQs

What is deadlock prevention? 

Deadlock prevention is a way to make sure that a deadlock, where processes get stuck waiting for each other and can’t move forward, never happens in a computer system. It sets up rules to manage how resources are used, so processes can’t get into a situation where they are stuck.

What is deadlock avoidance? 

Deadlock avoidance is a method used in computer systems to ensure that processes do not enter into a deadlock situation. Instead of just setting rules like in deadlock prevention, deadlock avoidance continuously monitors the state of the system and makes decisions on-the-fly to keep processes from getting stuck.

What are the 4 conditions for deadlock?

Four conditions of deadlock are:

  • Mutual Exclusion
  • Hold and Wait
  • No Preemption
  • Circular Wait


Previous Article
Next Article

Similar Reads

Difference between Deadlock Prevention and Deadlock Avoidance
Deadlock is a condition where a set of processes becomes stuck and waits infinitely for the resources which are hold by other processes. To handle these types of problems, we use two strategies - Deadlock Prevention and Deadlock Avoidance. Deadlock Prevention means blocking one of the conditions necessary for deadlock while deadlock avoidance refer
4 min read
Introduction to TimeStamp and Deadlock Prevention Schemes in DBMS
Deadlock occurs when each transaction T in a schedule of two or more transactions waiting for some item locked by some other transaction T' in the set. Thus, both end up in a deadlock situation, waiting for the other to release the lock on the item. Deadlocks are a common problem and we have introduced the problem while solving the Concurrency Cont
7 min read
Zombie Processes and their Prevention
Zombie state: When a process is created in UNIX using fork() system call, the parent process is cloned. If the parent process calls wait() system call, then the execution of the parent is suspended until the child is terminated. At the termination of the child, a 'SIGCHLD' signal is generated by the kernel which is delivered to the parent. Parent,
5 min read
Denial of Service and Prevention
Denial of Service (DoS) is a cyber-attack on an individual Computer or Website with the intent to deny services to intended users. Their purpose is to disrupt an organization's network operations by denying access to its users. Denial of service is typically accomplished by flooding the targeted machine or resource with surplus requests in an attem
6 min read
Path Traversal Attack and Prevention
A path traversal attack allows attackers to access directories that they should not be accessing, like config files or any other files/directories that may contains server's data not intended for public. Using a path traversal attack (also known as directory traversal), an attacker can access data stored outside the web root folder (typically /var/
2 min read
Format String Vulnerability and Prevention with Example
A format string is an ASCII string that contains text and format parameters. Example: // A statement with format stringprintf("my name is : %s\n", "Akash");// Output// My name is : Akash There are several format strings that specify output in C and many other programming languages but our focus is on C. Format string vulnerabilities are a class of
3 min read
What is Data Exfiltration? Definition and Prevention
Data exfiltration is also known by other terms like data extrusion, data exportation, or data theft. All these terms describe the unauthorized movement of data from a computer or another device. This can happen manually by someone with physical access to the computer, or it can be automated through malicious software over a network. Data exfiltrati
4 min read
What is a Boot Sector Virus? (Definition, Risks and Prevention)
A boot sector virus is a virus that infects either the boot sector of floppy discs or the Master Boot Record (MBR) of hard discs. It infects the part of a computer's hard drive that starts the operating system. The infected code starts when the boot sector virus system is booted from an infected disc, but once loaded, it infects subsequent floppy d
7 min read
Relation Between Number of Processes and Number of Resources to Prevent Deadlock
A set of blocked processes where each process is holding some resource and waiting to acquire some other resource held by another process in the set. This situation is called deadlock in the operating system. Deadlock can be prevented if the number of resource instances in a system is significantly larger than the number of processes asking for a r
3 min read
Deadlock Detection And Recovery
Deadlock Detection and Recovery is the mechanism of detecting and resolving deadlocks in an operating system. In operating systems, deadlock recovery is important to keep everything running smoothly. A deadlock occurs when two or more processes are blocked, waiting for each other to release the resources they need. Detection methods help identify w
6 min read
Deadlock, Starvation, and Livelock
Prerequisite - Deadlock and Starvation  Livelock occurs when two or more processes continually repeat the same interaction in response to changes in the other processes without doing any useful work. These processes are not in the waiting state, and they are running concurrently. This is different from a deadlock because in a deadlock all processes
6 min read
Difference between Deadlock and Starvation in OS
Deadlock is a condition wherein all the processes are holding one resource each and are waiting for another process to release another resource. Starvation is a state that prevents lower-precedence processes from getting the resources. Starvation arises when procedures with critical importance keep on utilizing the resources frequently. Therefore,
7 min read
Cross Site Scripting (XSS) Prevention Techniques
XSS or Cross-Site Scripting is a web application vulnerability that allows an attacker to inject vulnerable JavaScript content into a website. An attacker exploits this by injecting on websites that doesn't or poorly sanitizes user-controlled content. By injecting vulnerable content a user can perform (but not limited to), Cookie Stealing.Defacing
5 min read
Operating Systems | Deadlock | Question 1
Suppose n processes, P1, …. Pn share m identical resource units, which can be reserved and released one at a time. The maximum resource requirement of process Pi is Si, where Si > 0. Which one of the following is a sufficient condition for ensuring that deadlock does not occur? (A) A (B) B (C) C (D) D Answer: (C) Explanation: See Question 4 on foll
1 min read
Operating Systems | Deadlock | Question 2
Consider the following snapshot of a system running n processes. Process i is holding Xi instances of a resource R, 1 <= i <= n. currently, all instances of R are occupied. Further, for all i, process i has placed a request for an additional Yi instances while holding the Xi instances it already has. There are exactly two processes p and q su
1 min read
Chandy-Misra-Haas's Distributed Deadlock Detection Algorithm
Chandy-Misra-Haas's distributed deadlock detection algorithm is an edge chasing algorithm to detect deadlock in distributed systems. In edge chasing algorithm, a special message called probe is used in deadlock detection. A probe is a triplet (i, j, k) which denotes that process Pi has initiated the deadlock detection and the message is being sent
4 min read
Deadlock Ignorance in Operating System
In this article we will study in brief about what is Deadlock followed by Deadlock Ignorance in Operating System. What is Deadlock? If each process in the set of processes is waiting for an event that only another process in the set can cause it is actually referred as called Deadlock. In other words, one event which has to happen by one process wi
5 min read
Deadlock System model
Overview :A deadlock occurs when a set of processes is stalled because each process is holding a resource and waiting for another process to acquire another resource. In the diagram below, for example, Process 1 is holding Resource 1 while Process 2 acquires Resource 2, and Process 2 is waiting for Resource 1. System Model : For the purposes of dea
8 min read
Deadlock-Free Packet Switching
In computer networks deadlock is the most serious system failure. Deadlocks are situations in which packets are stuck in a loop and can never reach their destination no matter what sequence of moves are performed. Deadlock must be observed and carefully handled to avoid system failure. Most of the networks that we have today are packet switching ne
6 min read
Conditions for Deadlock in Operating System
A deadlock is a situation where a set of processes is blocked because each process is holding a resource and waiting for another resource acquired by some other process. In this article, we will discuss what is deadlock and the necessary conditions required for deadlock. What is Deadlock?Deadlock is a situation in computing where two or more proces
8 min read
Deadlock Detection Algorithm in Operating System
In operating systems, managing resources like memory, files, and processors is very important. Sometimes, processes (or programs) get stuck waiting for each other to release resources, leading to a situation called a deadlock. To handle deadlocks, operating systems use special methods called deadlock detection algorithms. These algorithms help iden
7 min read
Recovery from Deadlock in Operating System
In today's world of computer systems and multitasking environments, deadlock is an undesirable situation that can bring operations to a halt. When multiple processes compete for exclusive access to resources and end up in a circular waiting pattern, a deadlock occurs. To maintain the smooth functioning of an operating system, it is crucial to imple
8 min read
Introduction of Deadlock in Operating System
A deadlock is a situation where a set of processes is blocked because each process is holding a resource and waiting for another resource acquired by some other process. In this article, we will discuss deadlock, its necessary conditions, etc. in detail. What is Deadlock?Deadlock is a situation in computing where two or more processes are unable to
11 min read
MongoDB AND operator ( $and )
MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. ac
2 min read
Hardware Synchronization Algorithms : Unlock and Lock, Test and Set, Swap
Process Synchronization problems occur when two processes running concurrently share the same data or same variable. The value of that variable may not be updated correctly before its being used by a second process. Such a condition is known as Race Around Condition. There are a software as well as hardware solutions to this problem. In this articl
5 min read
Difference Between AND Gate and OR Gate
AND gate and OR gate are basic logic gates. AND gate outputs 1 when all inputs are 1 else output 0. OR gate outputs 1 when at least one input is 1 else output 0. The main difference between AND gate and OR gate is that AND gate represents logical conjunction whereas OR gate represents logical disjunction. In this article we will explore difference
4 min read
Calculation of address of element of 1-D, 2-D, and 3-D using row-major and column-major order
This article focuses on calculating the address of any element in a 1-Dimensional, 2-Dimensional, and 3-Dimensional array in Row major order and Column major order. Calculating the address of any element In the 1-D array:A 1-dimensional array (or single-dimension array) is a type of linear array. Accessing its elements involves a single subscript t
11 min read
Difference Between Store‑and‑Forward Switching and Cut‑Through Switching
Switching is a technique to transmit data between networks using switches that connect multiple LANs. Switches forward data packets based on MAC addresses, efficiently using bandwidth and reducing collisions. The three main types are: Circuit Switching: Dedicated path for the entire connection, used in traditional telephony.Message Switching: Entir
5 min read
Difference Between Stop and Wait, GoBackN and Selective Repeat
Flow control in networking manages the rate of data transmission between devices to ensure efficient processing and prevent data overflow. When a device receives more data than it can handle, it risks losing information or needing retransmission. Flow control protocols guide the sender on how much data to send, and typically require an acknowledgme
5 min read
How to Determine the Optimal MTU and MSS Size?
Transmission Control Protocol(TCP) is the most important protocol of the internet protocol suite. TCP is basically a connection-oriented protocol that is concerned with error control, flow control, and congestion control in the network to maintain the integrity of the data and make data transmission easier. TCP makes use of MTU (Maximum Transmissio
5 min read