0% found this document useful (0 votes)
3 views79 pages

OS Chapter -4

The document discusses the concept of deadlock in computing, defining it as a situation where processes are blocked, waiting for resources held by each other. It outlines the four necessary conditions for deadlock, methods for handling it, including prevention, avoidance, detection, and recovery, and introduces the Resource-Allocation Graph as a tool for visualizing resource allocation. Additionally, it explains the importance of maintaining a 'safe state' to prevent deadlocks and describes algorithms for resource allocation management.

Uploaded by

herid72018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views79 pages

OS Chapter -4

The document discusses the concept of deadlock in computing, defining it as a situation where processes are blocked, waiting for resources held by each other. It outlines the four necessary conditions for deadlock, methods for handling it, including prevention, avoidance, detection, and recovery, and introduces the Resource-Allocation Graph as a tool for visualizing resource allocation. Additionally, it explains the importance of maintaining a 'safe state' to prevent deadlocks and describes algorithms for resource allocation management.

Uploaded by

herid72018
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Chapter -4

Deadlock

Senait G. (MSc)
The Deadlock Problem
✓ A deadlock is a situation where a process or a set of processes is blocked,
waiting for some resource that is held by some other waiting process.

✓ Waiting a particular resource for infinite time with out progress.

✓ A set of blocked processes each holding a resource and waiting to acquire a

resource held by another process in the set.


Example:- System has 2 tape drives.

✓ P1 and P2 each hold one tape drive.

✓ If each process now requests another drive, the two processes will be in a
deadlocked state.
Bridge Crossing Example

✓ Traffic only in one direction.

✓ Each section of a bridge can be viewed as a resource.

✓ If a deadlock occurs, it can be resolved if one car backs up (preempt

resources and rollback).

✓ Several cars may have to be backed up if a deadlock occurs.


• Starvation is possible. why??
System Model
➢ A set of blocked processes each holding a resource and waiting to acquire a

resource held by another process in the set.

✓ A system consists of a finite number of resources to be distributed among a

number of competing processes.


➢ Resource types R1, R2, . . ., Rm (like CPU cycles, memory space, printers or
any other i/o devices, etc…)
➢ The resources may be either physical (printers, tape drives, memory space, and

CPU cycles) or logical (files and even semaphores).Semaphore: is a variable or


abstract data type that is used for controlling access by multiple processes to a
common resource in a concurrent system such as a multiprogramming operating
system.
Con’t…
➢ A process must request a resource before using it, and

must release the resource after using it.


➢ A process may utilize a resource in only the following sequence:

1. Request: If the request cannot be granted immediately, then the requesting


process must wait until it can acquire the resource.

2. Use: The process can operate on the resource (example, print on printer).

3. Release: The process releases the resource.


Con’t…

➢ The request and release of resources are system calls

(Examples: request and release device, open and close file,


and allocate and free memory system calls).
➢ Request and release of other resources can be accomplished

through the wait and signal operations on semaphores.


Deadlock characterization
✓ A deadlock situation can arise if the following four conditions hold
simultaneously in a system:
Mutual execution

Hold and wait

No preemption

Circular wait
Cont…
 Mutual exclusion- only one process at a time can use a resource. If another
process requests that resource, the requesting process must be delayed until the
resource has been released.

 Hold and wait- A process must be simultaneously holding at least one resource
and waiting for at least one resource that is currently being held by some other
process.

 No preemption- Resources cannot be preempted; that is a resource can be released


only voluntarily by the process holding it, after that process has completed its task.

 Circular Wait- There must be a circular chain of two or more processes, each of
which is waiting for a resource held by the next member of the chain.
Resource-Allocation Graph
✓ A deadlock is described in terms of a direct graph called a
system RAG
✓ A set of vertices V and a set of edges E.
✓ V is partitioned into two types:
◦ P = {P1, P2, …, Pn}, the set consisting of all the processes in
the system.
◦ R = {R1, R2, …, Rm}, the set consisting of all resource types
in the system.
✓ Request edge – directed edge Pi → Rj
✓ Assignment edge – directed edge Rj → Pi
Con’t…
 Process

 Resource type with 4 instances

 Pi requests instance of Rj Pi

 Pi is holding an instance of Rj Pi
Example of a Resource Allocation Graph

Process State:
✓ P1 is holding an instance of R2 and waiting for an

instance of R1.
✓ P2 is holding an instance of R1 and R2, and is

waiting for an instance of R3.


✓ P3 is holding an instance of R3.

• The graph does not contain any cycles.


Resource Allocation Graph With A Deadlock

• Two minimal cycles exist in the system:


✓ P1→R1→P2→R3→ P3→ R2→P1

✓ P2→R3→P3→R2→P2

• Processes P1, P2, P3 are deadlocked.


✓ P1 is waiting for P2 to release R1.

✓ P2 is waiting for R3 which is held by P3.

✓ P3 is waiting for P1 or P2 to release R2.


Resource Allocation Graph With A Cycle

✓ We have a cycle:

P1→R1→P3→R2→P1
✓P4 may release its instance of R2 and

that resource can then be allocated to P3


breaking the cycle.
 There is no deadlock on the above RAG.
Basic Facts
➢ If a resource-allocation graph does contain cycles AND each
resource category contains only a single instance, then a deadlock
exists.

➢ If a resource category contains more than one instance, then the


presence of a cycle in the resource-allocation graph indicates
the possibility of a deadlock, but does not guarantee one.
Methods for Handling Deadlocks
 Generally speaking we can deal with the deadlock problem in one of
four ways:
◦ Prevention, by structurally negating*one of the four required conditions.

◦ Dynamic avoidance by careful resource allocation.

◦ Detection and recovery. Let deadlocks occur, detect them, and take action.

◦ Just ignore the problem. Maybe if you ignore it, it will ignore you.
Deadlock Prevention

➢ Prevent any one of the four (4) conditions from happening.


➢ By ensuring that at least one of these conditions cannot hold, we can
prevent the occurrence of a deadlock.

✓ Do not allow one of the four conditions to occur.


1. Mutual Exclusion
 Some resources are inherently unshareable, for example, Printers. For unshareable
resources, processes require exclusive control of the resources.
 A mutual exclusion means that unshareable resources cannot be accessed
simultaneously by processes.
 Shared resources do not cause deadlock but some resources can't be shared among
processes, leading to a deadlock.
 For Example: read operation on a file can be done simultaneously by multiple
processes, but write operation cannot. Write operation requires sequential access, so,
some processes have to wait while another process is doing a write operation.
 It is not possible to eliminate mutual exclusion, as some resources are doesn't have

associated memory,

 For Example: Tape drive, as only one process can access data from a Tape drive at a time.

 For other resources like printers, we can use a technique called Spooling.

 Spooling: It stands for Simultaneous Peripheral Operations online.

 A Printer has associated memory which can be used as a spooler directory (memory that is

used to store files that are to be printed next).

 In spooling, when multiple processes request the printer, their jobs ( instructions of the

processes that require printer access) are added to the queue in the spooler directory.

 The printer is allocated to jobs on a first come first serve (FCFS) basis. In this way, the

process does not have to wait for the printer and it continues its work after adding its job to

the queue.
Cont…
Cont…
 Spooling suffers from two kinds of problems.

1. This cannot be applied to every resource.

2. After some point of time, there may arise a race condition between
the processes to get space in that spool.

3. It is not a full-proof method as after the queue becomes


full, incoming processes go in a waiting state.
2. Hold and Wait: Collect all resources before execution.
 Hold and wait condition lies when a process holds a resource
and waiting for some other resource to complete its task.
 Deadlock occurs because there can be more than one process
which are holding one resource and waiting for other in the
cyclic order.
To prevent deadlock, a process must be assigned all the
necessary resources before the execution starts.
 A process must not wait for any resource once the execution
has been started.
 By eliminating wait:
 The process specifies the resources it requires in advance
so that it does not have to wait for allocation
after execution starts.
 For Example: Process1 declares in advance that it
requires both Resource1 and Resource2
Cont…
 This can be implemented practically if a process declares all
the resources initially.
 This can't be done in the computer system because a process
can't determine necessary resources initially.

 Protocol 1: request all tape, disk, printer and hold for entire
execution; note printer will be idle for a long time.
Cont…
 The problem with the approach is:
1.Practically not possible. (As a process executes
instructions one by one, it cannot know about all
required resources before execution.)
2.Low resource utilization
3.Possibility of getting starved will be increases due to the
fact that some process may hold a resource for a very
long time.
3. No preemption

 Preemption is temporarily interrupting an executing task and


later resuming it.
 For example, if a process P1 is using a resource and a high
priority process P2 requests for the resource, process P1 is
stopped and the resources are allocated to P2.
 There are two ways to eliminate this condition by preemption:

1. If a process is holding some resources and waiting for other


resources, then it should release all previously held resources and put
a new request for the required resources again. The process can
resume once it has all the required resources.

 For example: If a process has resources R1, R2, and R3 and it is


waiting for resource R4, then it has to release R1, R2, and R3 and
put a new request of all resources again.
2. If a process P1 is waiting for some resource, and there is another
process P2 that is holding that resource and is blocked waiting for
some other resource.
 Then the resource is taken from P2 and allocated to P1. This way
process P2 is preempted and it requests again for its required
resources to resume the task. The above approaches are possible for
resources whose states are easily restored and saved, such as
memory and registers.
 These approaches are problematic as the process might be
actively using these resources and halting the process by
preempting can cause inconsistency.

 For example: If a process is writing to a file and its access is


revoked for the process before it completely updates the file,
the file will remain unusable and in an inconsistent state.

 Putting requests for all resources again is inefficient and time


consuming.
Con’t…
4. Circular Wait:
✓ In circular wait, two or more processes wait for resources in a circular order.

To eliminate circular wait, we assign a priority to each resource. A process can only
request resources in increasing order of priority.
Con’t…
Example: Let R={R1, R2, …, Rm} be the set of resource types.
✓ Assign to each resource type a unique integer number to compare two
resources and to determine whether one proceeds another in
ordering.

✓ For example: If the set of resource types R includes tape drives, disk
drives, and printers, then a priority might be defined as follows:

tape drive= 1; disk drive= 2; Printer= 3.


✓A protocol to prevent deadlocks: Each process can request resources
only in an increasing order of enumeration.
 It is difficult to assign a relative priority to resources, as
one resource can be prioritized differently by different
processes.
 For Example: A media player will give a lesser priority
to a printer while a document processor might give it a
higher priority. The priority of resources is different
according to the situation and use case.
Is practically possible?

 Among all the methods, violating Circular wait is the only approach that can
be implemented practically.
Deadlock Avoidance
✓ Deadlock Avoidance is a process used by the Operating System to avoid

Deadlock.

✓ Requires that the system has some additional a priori information about the use

of resources by processes
 how can Operating System avoid Deadlock?
 Operating System avoids Deadlock by knowing the maximum resources
requirements of the processes initially, and also Operating System knows the
free resources available at that time.
 Operating System tries to allocate the resources according to the process
requirements and checks if the allocation can lead to a safe state or an unsafe
state.
 If the resource allocation leads to an unsafe state, then Operating System does not
proceed further with the allocation sequence.
✓ Simplest and most useful model requires that each process declare
the maximum number of resources of each type that it may need.
✓ The deadlock-avoidance algorithm dynamically examines the
resource-allocation state to ensure that there can never be a circular-
wait condition.
✓ Resource-allocation state is defined by the number of available and
allocated resources, and the maximum demands of the processes.
Cont…
 The main difference between deadlock prevention and deadlock
avoidance is that the deadlock prevention ensures that at least
one of the necessary conditions to cause a deadlock will never
occur, while deadlock avoidance ensures that the system will not
enter an unsafe state.
Safe State

✓ When a process requests an available resource, system must decide if

immediate allocation leaves the system in a safe state.

✓ A state is safe if the system can allocate all resources requested by all

processes ( up to their stated maximums ) without entering a


deadlock state.
Cont…
 If a safe sequence does not exist, then the system is in an
unsafe state, which MAY lead to deadlock. ( All safe
states are deadlock free, but not all unsafe states lead to
deadlocks. )
Example one
 Consider a system with 12 tape drives and 3 processes, allocated as
follows in a table at state .

Q: Is this a safe state? What is the safe sequence?


 Available resource=total resource- allocated resource
 Available resource= 12-9= 3
Cont…
 First we have to find out the safe sequence
 So that, we can fulfill the request of P1, P0 and P2
respectively.

 <P1, P0, P2> satisfies the safety condition.


Or
 Yes, it is a safe state and the save sequence is <P1,P0,P2>
Example two
Q1: Is the following system safe?
 A system with 12 tape drives and 3 processes: P0, P1, P2
at state .
Cont…
 Available resource=total resource- allocated resource
 Available resource= 12-10= 2
 This sequence <P1, P0, P2> is unsafe; only P1 can be
satisfied. P0 and P2 must waits yielding to a deadlock.
Basic Facts
✓ If a system is in safe state ⇒ no deadlocks.

✓ If a system is in unsafe state ⇒ possibility

of deadlock.

✓ Avoidance ⇒ ensure that a system will

never enter in an unsafe state.


✓ Safe, unsafe , deadlock state spaces.
Avoidance algorithms
 Single instance of a resource type
✓ Use a resource-allocation graph

 Multiple instances of a resource type


✓ Use the banker’s algorithm
1. Resource-Allocation Graph Algorithm
✓ In addition to the request and assignment edges already described, we
introduce a new type of edge, called a claim edge.
✓ Claim edge Pi ----->Rj indicated that process Pi may request resource Rj for

future (represented by a dashed line)

✓ Claim edge converts to request edge when a process requests a resource.

✓ Request edge converted to an assignment edge when the resource is allocated to

the process

✓ When a resource is released by a process, assignment edge reconverts to a claim

edge.
Resource-Allocation Graph For Deadlock
Avoidance

✓ Figure 2 shows an unsafe state in a resource-allocation graph, because


there is a cycle in the graph.

✓ The resource-allocation graph algorithm is not applicable to a resource


allocation system with multiple instances of each resource type.
2. Banker’s Algorithm
✓ Banker’s algorithm is applicable to a resource-allocation system with multiple

instances of each type.

✓ From it’s name, it could be used in a banking system to ensure that the bank never

allocates its available cash such that it can no longer satisfy the needs of all
customers.(banks never run out of the resources or money and always been in a safe
state).
Data Structures for the Banker’s Algorithm

Let “n” be the number of processes and “m” be the number of resources
types. So we needs the following DS to implement Bankers algorithm.
Available: Vector of length “m” indicates the number of available resources
of each type.

If available [j] = k, there are k instances of resource type Rj available.

Max: An (n*m) matrix defines the maximum demands of each process.

If Max [i,j] = k, then process Pi may request at most k instances of resource


type Rj.
Con’t….
Allocation: An (n*m) matrix defines the number of resources of each
type currently allocated to each process.

If Allocation [i,j] = k then Pi is currently allocated k instances of Rj.


Need: An (n*m) matrix indicates the remaining resource need of each
process.

If Need [i,j] = k, then Pi may need k more instances of Rj to complete its


task.
Need [i,j] = Max[i,j] – Allocation [i,j].
Safety Algorithm
Step-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.

Step-2: Find an i such that both:


(a) Finish [i] = false
(b) Need i ≤ Work
If no such i (no process) exists, go to step 4.

Step-3: Finish[i] =true

Work = Work + Allocation i


go to step 2.
Step-4: If Finish [i] = true for all i, then the system is in a safe state
Resource-Request Algorithm for Process Pi
Request = request vector for process Pi.If Requesti [j]= k then process Pi wants k
instances of resource type Rj.
Step-1: If Requesti  Needi, go to step 2. Otherwise, raise error condition, since process
has exceeded its maximum claim.

Step-2: If Requesti  Available, go to step 3. Otherwise Pi must wait, since resources


are not available.
Step-3: Pretend to allocate requested resources to Pi by modifying the state as follows:
Available = Available - Requesti;
Allocationi = Allocationi + Requesti;
Needi = Needi – Requesti;
• If safe  the resources are allocated to Pi.
• If unsafe  Pi must wait, and the old resource-allocation state is restored
Example of Banker’s Algorithm
✓ 5 processes P0 through P4; 3 resource types A (10 instances), B (5
instances, and C (7 instances).

✓ Snapshot at time T0: we have the following resource allocation state.


Allocation Max Available
ABC ABC ABC
P0 010 753 3 32
P1 200 322
P2 302 902
P3 211 222
P4 002 433
Cont…
Q1: what is the need matrix?
Q2: Is the system in safe state?
Q3: If yes, find the safe sequence.
Answer
 Total resource= Total allocation + Available resource
 Need is defined to be Max – Allocation
◦ (Need [n][m]= Max [n][m] – Allocation[n][m])
Allocation Max. R.N Available Need
ABC ABC ABC ABC
P0 0 1 0 753 332 743
P1 2 0 0 322 532 122
P2 3 0 2 902 743 600
P3 2 1 1 222 745 011
P4 0 0 2 433 755 431
Safe sequence: <P1, P3 , P4 , P0, P2>
Yes, the system is in a safe state
In bankers algorithm inputs are:
◦ Processes
◦ Any 2 out of 3(Max, Need, Allocation)
◦ Available or Total no. of resources
Exercise 1:
Q: The following table is given:
Allocation Max Available
ABCD ABCD ABCD
P0 0 0 1 2 0012 15 2 0
P1 1 0 0 0 1750
P2 1 3 5 4 2356
P3 0 6 3 2 0652
P4 0 0 1 4 0656
Q1: Find the total number of resources?
Q2: what is the need matrix?
Q3: Is the system in safe state?
Q4: If yes, find the safe sequence?
Answer
Allocation Max Available Need
ABCD ABCD ABCD ABCD
P0 0 0 1 2 0012 15 2 0 0 0 0 0
P1 1 0 0 0 1750 15 3 2 0 7 5 0
P2 1 3 5 4 2356 2 8 8 6 1 0 0 2
P3 0 6 3 2 0652 2 14 11 8 0 0 2 0
P4 0 0 1 4 0656 2 14 12 12 0 6 4 2
 Total no of resource: 3 14 12 12
 System is in a Safe state
 Safe sequence is: <P0, P2, P3, P4,P1>
Deadlock Detection
✓ If a system does not employ a deadlock prevention algorithm or a
deadlock avoidance algorithm, then a deadlock situation may occur.

• Therefore, the system must provide:


– Detection: an algorithm that examines the state of the system to
determine whether a deadlock has occurred.
– Recovery: an algorithm to recover from the deadlock.

A detection and recovery scheme requires overhead that includes:


– Run-time costs of maintaining the necessary information.
– Executing the detection algorithm.
– The potential losses inherent in recovering from a deadlock.
Single Instance of Each Resource Type
✓ A deadlock detection algorithm uses a variant of the resource
allocation graph called wait-for graph.

✓ An edge from Pi to Pj in a wait-for graph implies that process Pi is


waiting for process Pj to release a resource that Pi needs.

✓ An edge Pi Pj exists in a wait-for graph if and only if the


corresponding resource-allocation graph contains two edges Pi Rq
and Rq Pj for some resource Rq.
Con’t…

✓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.
– Periodically invoke an algorithm that searches for a cycle in
the graph.
Resource-Allocation Graph and Wait-for
Graph
RAG Wait for graph

 There is no cycle in this wait for graph so that there is no deadlock


RAG wait for graph

 There is a deadlock, so now deadlock detection mechanism called.


 How frequently this deadlock detection algorithm would be called?
◦ Whenever a deadlock happens, Deadlock detection algorithm will be invoked.
Cont…
 The wait-for graph scheme is not applicable to a
resource allocation system with multiple instances of
each resource type.
Several Instances of a Resource Type
✓ The algorithm employs several time-varying data structures that are similar to
those used in the banker’s algorithm:

Note: “n” is number of processes in the system and “m” is the number of
resource types.

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] = k, then process Pi is requesting k more instances of resource type
Rj.
Detection Algorithm
Step-1: Let Work and Finish be vectors of length m and n,
respectively Initialize: Work = Available, For i = 1,2, …, n, if
Allocation i  0, then ,Finish[i] = false; otherwise, Finish[i] =
true.
Step-2: Find an index i such that both:
(a) Finish[i] = false
(b) Requesti  Work
If no such i exists, go to step 4.
Con't…
Step-3: Work = Work + Allocationi
Finish[i] = true
go to step 2.
Step-4: If Finish [i] = true for all i, then the system is in a safe state

If Finish[i] = false, for some i, 0  i  n, then the system is in


deadlock state.
Moreover, if Finish[i] = false, then Pi is deadlocked.
Example of Detection Algorithm
✓ Five processes P0 through P4; three resource types A (7 instances), B (2
instances), and C (6 instances).

✓ Snapshot at time T0: we have the following resource allocation state:


Allocation Request Available
ABC ABC ABC
P0 0 1 0 000 000
P1 2 0 0 202
P2 3 0 3 000
P3 2 1 1 100
P4 0 0 2 002
✓ Sequence <P0, P2, P3, P4, P1> will result in Finish [i] = true for all i.
Con't…
✓ P2 requests an additional instance of type C.
Request
ABC
P0 000
P1 202
P2 001
P3 100
P4 002
✓ State of system?
◦ Can reclaim resources held by process P0, but insufficient resources to
fulfill other processes; requests.
◦ Deadlock exists, consisting of processes P1, P2, P3, and P4.
Detection-Algorithm Usage
 When should we invoke the detection algorithm? The answer depends on two
factors:
1. How often is a deadlock likely to occur?
2. How many processes will be affected by deadlock when it happens?
✓ If deadlocks occur frequently, then the detection algorithm should be invoked
frequently.

✓ Resources allocated to deadlocked processes will be idle until the deadlock can
be broken.

✓ In addition, the number of processes involved in the deadlock cycle may grow.

✓ Deadlocks occur only when some process makes a request that cannot be
granted immediately.
Recovery from Deadlock
✓ When a detection algorithm determines that a deadlock exists, several

alternatives are available.

✓ One possibility is to inform the operator that a deadlock has occurred and to
let the operator deal with the deadlock manually.

✓ Another possibility is to let the system recover from the deadlock automatically.

 There are two options for breaking a deadlock:


– To abort one or more processes to break the circular wait (Process
Termination).
– To preempt some resources from one or more of deadlock processes
(Resource Preemption).
Recovery from Deadlock: Process Termination
 Two methods to eliminate deadlocks by aborting a process. In both
methods, the system reclaims all resources allocated to the
terminated processes:

A. Abort all deadlocked processes: Clearly will break the deadlock


cycle, but at great expense.

✓ The deadlocked processes may have computed for a long time, and
the results of these partial computations must be discarded and
probably will have to be recomputed later.
B. 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.
 Aborting a process may not be easy. If the process was in the midst
of updating a file, terminating it will leave that file in an incorrect
state.
Recovery from Deadlock: Resource Preemption
✓ If preemption is required to deal with deadlocks, then three issues need to be

addressed:

Selecting a victim: which resources and which processes are to be preempted?


(minimize cost)

Rollback: If we preempt a resource from a process, what should be done with that
process? We must roll back the process to some safe state, and restart it from
that state.

One process can be roll backed only 5x to minimize starvation.

Starvation: Same process may always be picked as victim, include number of


rollback in cost factor.
THANK YOU

You might also like