You are on page 1of 15

Deadlocks in Operating System

Deadlocks are a set of blocked processes each holding a resource and waiting to acquire a resource
held by another process.

In the above figure, process T0 has resource1, it requires resource2 to finish its execution. Similarly,
process T1 has resource2 and it also needs to acquire resource1 to finish its execution. In this way, T0
and T1 are in a deadlock because each of them needs the resource of others to complete their execution
but neither of them is willing to give up their resources.

In General, a process must request a resource before using it and it must release the resource after using
it. And any process can request as many resources as it requires to complete its designated task. And there
is a condition that the number of resources requested may not exceed the total number of resources
available in the system.

Basically in the Normal mode of Operation utilization of resources by a process is in the following
sequence:

1. Request: Firstly, the process requests the resource. In a case, if the request cannot be granted
immediately(e.g: resource is being used by any other process), then the requesting process must
wait until it can acquire the resource.
2. Use: The Process can operate on the resource ( e.g: if the resource is a printer then in that case
process can print on the printer).
3. Release: The Process releases the resource.

• Differences between starvation and deadlock.

Starvation Deadlock

When all the low priority processes got blocked, while the high Deadlock is a situation that occurs when one
priority processes execute then this situation is termed Starvation. of the processes got blocked.

Starvation is a long waiting but it is not an infinite process. Deadlock is an infinite process.

Not every starvation needs to be a deadlock. There is starvation in every deadlock.

Starvation is due to uncontrolled priority and resource During deadlock, preemption and circular
management. wait does not occur simultaneously.

The occurrence of deadlock can be detected by the resource scheduler.

Now in the next section, we will cover the conditions that are required to cause deadlock.

• Necessary Conditions

The deadlock situation can only arise if all the following four conditions hold simultaneously:

1. Mutual Exclusion

According to this condition, at least one resource should be non-shareable (non-shareable resources are
those that can be used by one process at a time.)

2. Hold and wait

According to this condition, A process is holding at least one resource and is waiting for additional
resources.
3. NO preemption

Resources cannot be taken from the process because resources can be released only voluntarily by the
process holding them.

4. Circular wait

In this condition, the set of processes is waiting for each other in the circular form. The above four
conditions are not completely independent as the circular wait condition implies the hold and wait for
condition. We emphasize the fact that all four conditions must hold for a deadlock. Deadlock conditions
can be avoided with the help of several methods. Let us take a look at some of the methods.

• Methods For Handling Deadlocks

Methods that are used to handle the problem of deadlocks are as follows:

1. Ignoring the Deadlock

According to this method, it is assumed that deadlock would never occur. This approach is used by many
operating systems where they assume that deadlock will never occur which means operating systems
simply ignores the deadlock. This approach can be beneficial for those systems that are only used for
browsing and normal tasks. Thus, ignoring the deadlock method can be useful in many cases but it is not
the perfect order to remove the deadlock from the operating system.

2. Deadlock Prevention

As we have discussed in the above section, all four conditions: Mutual Exclusion, Hold and Wait, No
preemption, and circular wait if held by a system then cause a deadlock to occur. The main aim of the
deadlock prevention method is to violate anyone condition among the four; because if any of one
condition is violated then the problem of deadlock will never occur. As the idea behind this method is
simple but the difficulty can occur during the physical implementation of this method in the system.

4. Avoiding the Deadlock

This method is used by the operating system to check whether the system is in a safe state or an unsafe
state. This method checks every step performed by the operating system. Any process continues its
execution until the system is in a safe state. Once the system enters into an unsafe state, the operating
system has to take a step back.

Basically, with the help of this method, the operating system keeps an eye on each allocation and makes
sure that allocation does not cause any deadlock in the system.

5. Deadlock detection and recovery

With this method, the deadlock is detected first by using some algorithms of the resource-allocation graph.
This graph is mainly used to represent the allocations of various resources to different processes. After
the detection of a deadlock, several methods can be used to recover from that deadlock.

One way is preemption by the help of which a resource held by one process is provided to another
process.

The second way is to roll back, as the operating system keeps a record of the process state and it can
easily make a processed roll back to its previous state due to which deadlock situation can be easily
eliminated.

The third way to overcome the deadlock situation is by killing one or more processes.

Deadlock Prevention in Operating System

As we are already familiar with all the necessary conditions for a deadlock. In brief, the conditions are as
follows:

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

let us take an example of a chair, as we know that a chair always stands on its four legs. Likewise, for the
deadlock problem, all the above given four conditions are needed. If any one leg of the chair gets broken,
then definitely it will fall. The same is the situation with the deadlock if we become able to violate any
condition among the four and do not let them occur together then there can be prevented the deadlock
problem.

We will elaborate deadlock prevention approach by examining each of the four necessary conditions
separately.
• Mutual Exclusion

This condition must hold for non-sharable resources. For example, a printer cannot be simultaneously
shared by several processes. In contrast, Sharable resources do not require mutually exclusive access and
thus cannot be involved in a deadlock. A good example of a sharable resource is Read-only files because
if several processes attempt to open a read-only file at the same time, then they can be granted
simultaneous access to the file.

A process need not wait for the sharable resource. Generally, deadlocks cannot be prevented by denying
the mutual exclusion condition because some resources are intrinsically non-sharable.

• Hold and Wait

Hold and wait condition occurs when a process holds a resource and is also waiting for some other
resource to complete its execution. Thus if we did not want the occurrence of this condition then we must
guarantee that when a process requests a resource, it does not hold any other resource.

Some protocols can be used to ensure that the Hold and Wait condition never occurs:

• According to the first protocol; Each process must request and gets all its resources before the
beginning of its execution.
• The second protocol allows a process to request resources only when it does not occupy any
resource.

Differences between these two protocols:

We will consider a process that mainly copies data from a DVD drive to a file on disk, sorts the file, and
then prints the results to a printer. If all the resources must be requested at the beginning of the process
according to the first protocol, then the process requests the DVD drive, disk file, and printer initially. It
will hold the printer during its entire execution, even though the printer is needed only at the end.
While the second method allows the process to request initially only the DVD drive and disk file. It copies
the data from the DVD drive to the disk and then releases both the DVD drive and the disk file. The
process must then again request the disk file and printer. After copying the disk file to the printer, the
process releases these two resources as well and then terminates.

Disadvantages of Both Protocols

o Utilization of resources may be low, since resources may be allocated but unused for a long period.
In the above-given example, for instance, we can release the DVD drive and disk file and again
request the disk file and printer only if we can be sure that our data will remain on the disk file.
Otherwise, we must request all the resources at the beginning of both protocols.
o There is a possibility of starvation. A process that needs several popular resources may have to
wait indefinitely because at least one of the resources that it needs is always allocated to some
other process.

• No Preemption

The third necessary condition for deadlocks is that there should be no preemption of resources that have
already been allocated. To ensure that this condition does not hold the following protocols can be used :

• According to the First Protocol: "If a process that is already holding some resources requests
another resource and if the requested resources cannot be allocated to it, then it must release all
the resources currently allocated to it."
• According to the Second Protocol: "When a process requests some resources, if they are available,
then allocate them. If in case the requested resource is not available then we will check whether it
is being used or is allocated to some other process waiting for other resources. If that resource is
not being used, then the operating system preempts it from the waiting process and allocates it to
the requesting process. And if that resource is being used, then the requesting process must wait".

The second protocol can be applied to those resources whose state can be easily saved and restored later
for example CPU registers and memory space, and cannot be applied to resources like printers and tape
drivers.

• Circular Wait

The Fourth necessary condition to cause deadlock is circular wait, To ensure violate this condition we can
do the following:
Assign a priority number to each resource. There will be a condition that any process cannot request a
lesser priority resource. This method ensures that not a single process can request a resource that is being
utilized by any other process and due to this no cycle will be formed.

Example: Assume that R5 resource is allocated to P1, if next time P1 asks for R4, R3 that are lesser than
R5; then such request will not be granted. Only the request for resources that are more than R5 will be
granted.

Necessary Practical
S.No Approach
Conditions Implementation

1 Mutual Exclusion The approach used to violate this condition is spooling. Not possible

To violate this condition, the approach is to request all the


2 Hold and wait Not possible
resources for a process initially

To violate this condition, the approach is: to snatch all the


3 No Preemption Not possible
resources from the process.

This approach is to assign priority to each resource and


4 Circular Wait possible
order them numerically

Deadlock Avoidance

The deadlock Avoidance method is used by the operating system to check whether the system is in a
safe state or an unsafe state and to avoid the deadlocks, the process just needs to tell the operating
system about the maximum number of resources a process can request to complete its execution.

In this method, the request for any resource will be granted only if the resulting state of the system
doesn't cause any deadlock in the system. This method checks every step performed by the operating
system. Any process continues its execution until the system is in a safe state. Once the system enters
into an unsafe state, the operating system has to take a step back.

With the help of a deadlock-avoidance algorithm, you can dynamically assess the resource-allocation
state so that there can never be a circular-wait situation.

According to the simplest and most useful approach, any process should declare the maximum number
of resources of each type it will need. The algorithms of deadlock avoidance mainly examine the
resource allocations so that there can never be an occurrence of circular wait conditions.
Deadlock avoidance can mainly be done with the help of Banker's Algorithm.

▪ Safe State and Unsafe State

A state is safe if the system can allocate resources to each process( up to its maximum requirement) in
some order and still avoid a deadlock. Formally, a system is in a safe state only, if there exists a safe
sequence. So a safe state is not a deadlocked state and conversely a deadlocked state is an unsafe state.

In an Unsafe state, the operating system cannot prevent processes from requesting resources in such a
way that any deadlock occurs. Not all unsafe states need to be deadlocks; an unsafe state may lead to a
deadlock.

The above Figure shows the Safe, unsafe, and deadlocked state spaces

Deadlock Avoidance Example

Let us consider a system having 12 magnetic tapes and three processes P1, P2, and P3. Process P1
requires 10 magnetic tapes, process P2 may need as many as 4 tapes, and process P3 may need up to 9
tapes. Suppose at a time to, process P1 is holding 5 tapes, process P2 is holding 2 tapes and process P3
is holding 2 tapes. (There are 3 free magnetic tapes)

Processes Maximum Needs Current Needs

P1 10 5

P2 4 2

P3 9 2
So at time t0, the system is in a safe state.The sequence is <P2,P1,P3> satisfies the safety
condition.Process P2 can immediately be allocated all its tape drives and then return them. After the
return the system will have 5 available tapes, then process P1 can get all its tapes and return them ( the
system will then have 10 tapes); finally, process P3 can get all its tapes and return them (The system
will then have 12 available tapes).

A system can go from a safe state to an unsafe state. Suppose at time t1, process P3 requests and is
allocated one more tape. The system is no longer in a safe state. At this point, only process P2 can be
allocated all its tapes. When it returns them the system will then have only 4 available tapes.Since P1 is
allocated five tapes but has a maximum of ten so it may request 5 more tapes. If it does so, it will have
to wait because they are unavailable. Similarly, process P3 may request its additional 6 tapes and have
to wait which then results in a deadlock.

The mistake was granting the request from P3 for one more tape. If we made P3 wait until either of the
other processes had finished and released its resources, then we could have avoided the deadlock

Note: In a case, if the system is unable to fulfill the request of all processes then the state of the system
is called unsafe.

The main key of the deadlock avoidance method is whenever the request is made for resources then the
request must only be approved only in the case the resulting state is safe.

▪ Resource allocation - graph algorithm

If we have a resource-allocation system with only one instance of each resource type, we can use a
variant of the resource-allocation graph for deadlock avoidance. In addition to the request and
assignment edges already described, we introduce a new type of edge, called a claim edge. A claim edge
Pi → Rj indicates that process Pi may request resource Rj at some time in the future. This edge
resembles a request edge in direction but is represented in the graph by a dashed line. When process Pi
requests resource Rj, the claim edge Pi → Rj is converted to a request edge.

Similarly, when a resource Rj is released by Pi, the assignment edge Rj → Pi is reconverted to a

claim edge Pi → Rj. We note that the resources must be claimed a priori in the system. That is before
process Pi starts executing, all its claim edges must already appear in the resource-allocation graph. We
can relax this condition by allowing a claim edge Pi → Rj to be added to the graph only if all the edges
associated with process Pi are claim edges.
Now suppose that process Pi requests resource Rj. The request can be granted only if converting the
request edge Pi → Rj to an assignment edge Rj → Pi does not result in the formation of a cycle in the
resource-allocation graph. We check for safety by using a cycle-detection algorithm. An algorithm for
detecting a cycle in this graph requires an O(n2) operation, where n is the number of processes in the
system. If no cycle exists, then the allocation of the resource will leave the system in a safe state. If a
cycle is found, then the allocation will put the system in an unsafe state. In that case, process Pi will
have to wait for its requests to be satisfied.

▪ Banker's Algorithm

When a new process enters the system, it must declare the maximum number of instances of each
resource type that it may need. This number may not exceed the total number of resources in the system.
When a user requests a set of resources, the system must determine whether the allocation of these
resources will leave the system in a safe state. If it will, the resources are allocated; otherwise, the
process must wait until some other process releases enough resources.

Several data structures must be maintained to implement the banker’s algorithm. We need the following
data structures, where n is the number of processes in the system and m is the number of resource types:

• Available Vector: A vector of length m indicates the number of available resources of each type. If
Available[j] equals k, then k instances of resource type Rj are available.

• Max Matrix: An n × m matrix defines the maximum demand of each process. If Max[i][j] equals k,
then process Pi may request at most k instances of resource type Rj .
• Allocation Matrix: An n × m matrix defines the number of resources of each type currently allocated
to each process. If Allocation[i][j] equals k, then process Pi is currently allocated k instances of resource
type Rj .

• Need Matrix: An n × m matrix indicates the remaining resource need of each process. If Need[i][j]
equals k, then process Pi may need k more instances of resource type Rj to complete its task. Note that
Need[i][j]= Max[i][j] − Allocation[i][j].

Safety Algorithm:

We can now present the algorithm for finding out whether or not a system is in a safe state. This
algorithm can be described as follows:

1. Let Work and Finish be vectors of length m and n, respectively. Initialize


Work = Available and Finish[i] = false for i = 0, 1, ..., n − 1.
2. Find an index i such that both
a. Finish[i] == false
b. Needi ≤ Work
If no such i exists, go to step 4.
3. Work = Work + Allocationi
Finish[i] = true
Go to step 2.
4. If Finish[i] == true for all i, then the system is in a safe state.
This algorithm may require an order of m × n2 operations to determine whether a state is safe.

Resource-Request Algorithm:

Next, we describe the algorithm for determining whether requests can be safely granted. Let Requesti be
the request vector for process Pi. If Requesti [ j] == k, then process Pi wants k instances of resource type
Rj .When a request for resources is made by process Pi ,

the following actions are taken:


1. If Requesti ≤ Needi , go to step 2. Otherwise, raise an error condition, since the process has
exceeded its maximum claim.
2. If Requesti ≤ Available, go to step 3. Otherwise, Pi must wait, since the resources are not
available.
3. Have the system pretend to have allocated the requested resources to process Pi by modifying the
state as follows:
Available = Available - Requesti ;
Allocationi = Allocationi + Requesti ;
Needi = Needi - Requesti ;

If the resulting resource-allocation state is safe, the transaction is completed, and process Pi is allocated
its resources. However, if the new state is unsafe, then Pi must wait for a Request, and the old resource-
allocation state is restored.

Deadlock Detection and Recovery

If a system does not employ either deadlock prevention or a deadlock-avoidance algorithm, then a
deadlock

situation may occur. In this environment, the system may provide:

• An algorithm that examines the state of the system to determine whether a deadlock has occurred

• An algorithm to recover from the deadlock.

Deadlock Detection

Detection of deadlock can be done in two situations one is detecting deadlock in a system with a
single instance of

each resource type and the second is detecting deadlock in a system with multiple instances of each
resource type.

▪ Single Instance of Each Resource Type:

If all resources have only a single instance, then we can define a deadlock detection algorithm that

uses a variant of the resource-allocation graph, called a wait-for graph. We obtain this graph from

the resource-allocation graph by removing the resource nodes and collapsing the appropriate edges.

A deadlock exists in the system if and only if the wait-for graph contains a cycle. To detect

deadlocks, the system needs to maintain the wait-for graph and periodically invoke an algorithm

that searches for a cycle in the graph. An algorithm to detect a cycle in a graph requires an O(n2)
operations, where n is the number of vertices in the graph.

▪ Several Instances of a Resource Type:

The wait-for graph scheme does not apply to a resource-allocation system with multiple instances

of each resource type. We turn now to a deadlock detection algorithm that applies to such a

system. The algorithm employs several time-varying data structures that are similar to those used in

the banker’s algorithm.

• Available: A vector of length m indicates the number of available resources of each type.
• Allocation: An n × m matrix defines the number of resources of each type currently allocated to
each process.
• Request: An n × m matrix indicates the current request of each process. If Request[i][j] equals k,
then process Pi is requesting k more instances of resource type Rj.

The detection algorithm described here simply investigates every possible allocation sequence for the
processes that remain to be completed.

1. Let Work and Finish be vectors of length m and n, respectively. Initialize


Work = Available. For i = 0, 1, ..., n-1, if Allocationi≠ 0, then Finish[i] = false;
otherwise, Finish[i] = true.
2. Find an index i such that both
a. Finish[i] == false
b. Requesti ≤ Work
If no such i exists, go to step 4.
3. Work = Work + Allocationi
Finish[i] = true
Go to step 2.
4. If Finish[i] == false for some i, 0 ≤ i < n, then the system is in a deadlocked state. Moreover, if
Finish[i] == false, then process Pi is deadlocked.

This algorithm requires an order of m × n2 operations to detect whether the system is in a deadlocked
state.

Deadlock Recovery

When a detection algorithm determines that a deadlock exists let the system recover from the deadlock
automatically. There are two options for breaking a deadlock. One is simply to abort one or more
processes to break the circular wait. The other is to pre-empt some resources from one or more of the
deadlocked processes.

To eliminate deadlocks by aborting a process, we use one of two methods. In both methods, the system
reclaims all resources allocated to the terminated processes.

• Abort all deadlocked processes: This method clearly will break the deadlock cycle, but at great
expense; the deadlocked processes may have been computed for a long time, and the results of these
partial computations must be discarded and probably will have to be recomputed later.

• Abort one process at a time until the deadlock cycle is eliminated: This method incurs considerable
overhead since after each process is aborted, a deadlock-detection algorithm must be invoked to
determine whether any processes are still deadlocked.

we should abort those processes to recover the system from deadlock whose termination will give

the minimum cost. Many factors may affect which process is chosen, including:

1. What is the priority of the process is.


2. How long the process has computed and how much longer the process will compute before
completing its designated task.
3. How many and what types of resources the process has used (for example, whether the resources
are simple to preempt)
4. How many more resources the process needs to complete
5. How many processes will need to be terminated
6. Whether the process is interactive or batch

To eliminate deadlocks using resource preemption, we successively preempt some resources from
processes and give these resources to other processes until the deadlock cycle is broken. If preemption
is required to deal with deadlocks, then three issues need to be addressed:

1. Select a victim. Which resources and which processes are to be preempted? As in process
termination, we must determine the order of preemption to minimize cost. Cost factors may include
such parameters as the number of resources a deadlocked process is holding and the amount of time the
process has thus far consumed during its execution.

2. Rollback. If we pre-empt a resource from a process, what should be done with that process? It cannot
continue with its normal execution; it is missing some needed resources. We must roll back the process
to some safe state and restart it from that state. Since, in general, it is difficult to determine what a safe
state is, the simplest solution is a total rollback: abort the process and then restart it. Although it is more
effective to roll back the process only as far as necessary to break the deadlock, this method requires the
system to keep more information about the state of all running processes.
3. Starvation. How do we ensure that starvation will not occur? That is, how can we guarantee that
resources will not always be pre-empted from the same process? In a system where victim selection is
based primarily on cost factors, the same process may be always picked as a victim. As a result, this
process never completes its designated task—a starvation situation that must be dealt with in any
practical system. We must ensure that a process can be picked as a victim only a (small) finite number
of times. The most common solution is to include the number of rollbacks in the cost factor.

When a detection algorithm determines that a deadlock exists then there are several available
alternatives. There is one possibility and that is to inform the operator about the deadlock and let him
deal with this problem manually.

You might also like