Вы находитесь на странице: 1из 26

2/18/2020

Operating System
B. Tech.
Delhi Technological university
Deadlocks
Instructor: Divyashikha Sethia

Divyashikha Sethia (DTU) 1

Deadlocks
a) The Deadlock Problem
b) System Model
c) Deadlock Characterization
d) Methods for Handling Deadlocks
e) Deadlock Prevention
f) Deadlock Avoidance
g) Deadlock Detection
h) Recovery from Deadlock

1
2/18/2020

Chapter Objectives
a) To develop a description of deadlocks, which prevent
sets of concurrent processes from completing their tasks

b) To present a number of different methods for


preventing or avoiding deadlocks in a computer system.

The Deadlock Problem


• In multiprogramming environment, several processes may compete for finite
number of resources.
• Process requests resources; and if resources are not available at that time,
process enters waiting state.
• Sometimes, a waiting process is never again able to change state, because
the resources it has requested are held by other waiting processes -
deadlock.
a) Example
– System has 2 tape drives.
– P1 and P2 each hold one tape drive and each needs another one.
b) Example
– semaphores A and B, initialized to 1
P0 P1
wait (A); wait(B)
wait (B); wait(A)

2
2/18/2020

Bridge Crossing Example

a) Traffic only in one direction.


b) Each section of a bridge can be viewed as a resource.
c) If a deadlock occurs, it can be resolved if one car backs up (preempt
resources and rollback).
d) Several cars may have to be backed up if a deadlock occurs.
e) Starvation is possible.

System Model
• System may consists of finite number of resources to be distributed among
number of competing processes. Resources are partitioned into several
types, each consisting of some number of identical instances.
• Memory space, CPU cycles, files, and I/O devices (such as printers and
DVD drives) are examples of resources types.
• If system has two CPUs, then instances of CPU are two.
• Process must request resource before using it and must release resource
after using it.
• Process may request as many resources as required for a task.
• Number of resources requested may not exceed the total number of
resources available in the system. i.e process cannot request three printers
if the system has only two.

3
2/18/2020

System Model (Cont.)


Process may utilize a resource in the following sequence:

1. Request: If the request cannot be granted immediately, process must


wait until it can acquire the resource.
2. Use: The process can operate on the resource( for example, if the
resource is a printer, the process can print on the printer).
3. Release: The process releases the resource.

Request and release of resources system calls:


Examples are the request() and release() device, open() and close() file,
and allocate() and free() memory system calls.
Other resource sequence not not managed by the operating system can
be accomplished through the wait() and signal() operations on
semaphores.

Deadlock Characterization
In a deadlock, processes never finish executing, and system resources are tied
up preventing other jobs from starting.
Now, we look more closely at features that characterize deadlocks;
Necessary Conditions: A deadlock situation can arise if the following four
conditions hold simultaneously in a system:
a) Mutual exclusion: At least one resource must be held in non-sharable
mode - only one process at a time can use a resource. If another process
requests that resource, requesting process must be delayed until resource
has been released.

b) Hold and wait: Process must be holding at least one resource and is
waiting to acquire additional resources that are currently being held by other
processes.

c) No preemption: Resources cannot be preempted; that is, a resource can be


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

4
2/18/2020

Deadlock Characterization (Cont.)


d) Circular wait: A set {P0, P1, …, Pn} of waiting processes must exist such that
P0 is waiting for resource held by P1, P1 is waiting for a resource held by P2,
…, Pn–1 is waiting for a resource held by Pn, and Pn is waiting for a resource
that is held by P0.

All four conditions must hold for a deadlock to occur.

The circular-wait condition implies the hold-and-wait condition, so the four


conditions are not completely independent

Resource-Allocation Graph
Deadlocks can be described more precisely in terms of a directed graph called a
system resource-allocation graph. This graph consists of a set of vertices V
and a set of edges E;
a) The set of vertices V is partitioned into two different types of nodes:
– 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.
b) Requested edge: Directed edge from process Pi to resource type Rj Pi  Rj;
- signifies process Pi has requested an instance of resource type Rj and is
currently waiting for that resource.
a) Assignment edge: Directed edge from resource type Rj to process Pi Rj  Pi;
- signifies that instance of resource type Rj has been allocated to process Pi.
a) Pictorially, represent each process Pi as a circle and each resource type Rj as
rectangle. Since resource type Rj may have more than one instance, we
represent each such instance as a dot within a rectangle. Note that a request
edge points to only the rectangle Rj, whereas an assignment edge must also
designate one of the dots in the rectangle.

5
2/18/2020

Resource-Allocation Graph (Cont.)


e) Process

f) Resource Type with 4 instances

g) Pi requests instance of Rj
Pi
Rj

h) Pi is holding an instance of Rj
Pi
Rj

Example of a Resource Allocation Graph

6
2/18/2020

Basic Facts
With the help of following facts, we can detect a deadlock within a
given system;
a) If the system resource-allocation graph contains no cycles 
no deadlock .
b) If graph contains a cycle 
– if only one instance per resource type, then deadlock.
– if several instances per resource type, then there is a
possibility of deadlock.

Resource Allocation Graph With A Deadlock

Deadlock since P3 requested instance of R2


Two cycles exist:
P1->R1->P2->R3->P3->R2->P1
P2->R3->P3->R2->P2
P1,P2,P3 are deadlocked
Divyashikha Sethia (DTU) 14

7
2/18/2020

Resource Allocation Graph With A Cycle But No Deadlock

P4 may release its instance of resource R2


Resource can then be allocated to P3 breaking
cycle

Divyashikha Sethia (DTU) 15

Methods for Handling Deadlocks


We can deal with the deadlock problem in one of the three ways:

a) We can use a protocol to prevent or avoiding deadlock, ensuring that the


system will never enter a deadlock state.

b) We can allow the system to enter a deadlock state, detect it, and then
recover.

c) We can ignore the problem altogether and pretend that deadlocks never
occur in the system.

The third solution is the one used by most operating systems, including UNIX
and Windows. – Application developers need to handle deadlocks

8
2/18/2020

Deadlock Prevention
Deadlock prevention provides a set of methods for ensuring that at least one of
the necessary conditions cannot hold. These methods prevent deadlocks by
constraining how requests for resources can be made.
Now, we briefly discuss these methods;

a) Mutual Exclusion
- Condition must hold for non-sharable resources eg:printer cannot be simultaneously
shared by several processes.
- Sharable resources, do not require mutually exclusive access and thus cannot be
involved in a deadlock. Read only files are a good example of a sharable resource. If
several processes attempt to open a read-only file at the same time, they can be
granted simultaneous access to the file.

Deadlock Prevention (Cont.)


b) Hold and Wait – To ensure that the hold-and-wait condition never occurs in the
system, we must guarantee that, whenever a process requests a resource, it does not
hold any other resources.
Protocols:
i) Process must request and be allocated all its resources before it begins execution.
(system calls requesting resources must precede all other system calls
Eg: Copy file fom DVD to file on disk, sort file and print
Requests resources DVD driv, disk and printer in the beginning and hold them till
the end. – printer held for entire duration
ii) Process to request resources only when it has none. i.e it may request some resource
and use them. But before it can request additional resources, it must release all the
resources that it currently owns.
Request DVD and disk in the beginning. Release them and then request disk and
printer.
Two main disadvantages:
 Low resource utilization: resources may be allocated but unused for long period
 Starvation is possible: Process needs several popular resources and may have to
wait long since one of the resources is always unavailable.

9
2/18/2020

Deadlock Prevention (Cont.)


c) No Preemption –To ensure that this condition does not hold, we can use
following protocol:

– If process is holding some resources and requests another resource that


cannot be immediately allocated to it, then all resources currently
being held are preempted. i.e these resources are released.

– Preempted resources are added to list of resources for which the


process is waiting and process will be restarted only when it can
regain its old resources, as well as the new ones that it is requesting.

Deadlock Prevention (Cont.)


d) circular wait: To ensure that this condition never holds is to impose a
total ordering of all Resource type and to require that each process requests
resources in an increasing order of enumeration.
Let R={R1 R2,…., Rm} be set of resource types.
Assign each resource type unique integer number
- allows to compare two resources
- determine whether one precedes another in our ordering.
Eg: F(tape) =1 F(disk) = 5 F(printer) = 12
Process can request resources only in an increasing order of enumeration
First request all instances of resource with priority Ri
Only then can request resources with priority Rj (Rj > Ri)

10
2/18/2020

Difference between Prevention and


Avoidance
Prevention puts restraints on how requests can be made by ensuring that of four
conditions cannot occur and hence prevents deadlock to occur
- Disadvantage: Low device utilization and system throughput

Avoidance: by knowing the complete requirement of resources for processes system


can decide for each request if process should wait in order to avoid deadlock in future
Deadlock Prevention:
•Preventing deadlocks by constraining how requests for resources can be
made in the system and how they are handled (system design).
•The goal is to ensure that at least one of the necessary conditions for
deadlock can never hold.
Deadlock Avoidance:
•The system dynamically considers every request and decides whether it is
safe to grant it at this point,
•The system requires additional apriori information regarding the overall
potential use of each resource for each process.
•Allows more concurrency.

Similar to the difference between a traffic light and a police officer directing traffic.

Deadlock Avoidance
Requires OS be given in advance additional information concerning which
resources a process will request and use.
OS decides for each request whether or not process should wait.
Must consider resources currently available, resources currently allocated to
each process, and the future requests and releases of each process.
Simple Model:
•Each process must declare maximum num of resources of each type that it may
need.
• Algorithm dynamically examines resource-allocation state to ensure that a
circular-wait condition can never exists
•Resource-allocation state is defined by number of available and allocated
resources and maximum demands of the processes.
Two deadlock avoidance algorithms:
1.Safe state;
2.Resource-Allocation-Graph Algorithm.

11
2/18/2020

Safe State
A state is safe if system can allocate resources to each process (up to its
maximum) in some order and still avoid a deadlock.
System is in safe state only if there exists a safe sequence.

A safe sequence of processes < P1, P2,…, Pn > is a safe sequence for the current
allocation state if, for each Pi, resource requests that Pi can still make can be
satisfied by the currently available resource plus the resources held by all Pj,
with j<i.
If resources that Pi needs are not immediately available ,then Pi can wait until
all Pj has finished.
When they have finished, Pi can obtain all of its needed resources, complete its
designated task, return its allocated resources and terminate
When Pi terminate , Pi+1 can obtain its needed resources, and so on.
If no such sequence exists, then system state is said to be unsafe.

Safe, Unsafe , Deadlock State


A safe state is not a deadlocked state.

Conversely, a deadlocked state is an unsafe state, but not all unsafe states are deadlocks.

Divyashikha Sethia (DTU) 24

12
2/18/2020

Safe State Example


•Number of tapes : 12, Processes: P0,P1,P2
•At time t0 current needs is the number of tapes being held by each process
•Hence free tapes: 3
Max Needs Current Holding
P0 10 5
P1 4 2
P2 9 2
Sate of system at t0: Safe? Sequence <P1,P0,P2> satisfies safety condition

25

Divyashikha Sethia (DTU)

Safe State Example

Sate of system at t0: Safe? Sequence <P1,P0,P2> satisfies safety condition


System could move from Safe - >Unsafe state eg: transition at time t1 P2 requests 1
more Hence: Free Tapes: 2

Max Needs Current Holding


P0 10 5
P1 4 2
P2 9 2+1

Only P1 can proceed


After P1 free disks: 4
But P0 requires 5 and P2 requires 6 Both would wait and lead to a deadlock
To avoid Deadlock ensure at every resource allocation that the state will be safe
Resource utilization would be low since process may have to wait even if resources
are available to avoid unsafe state.

Allocation to be done carefully!


26

Divyashikha Sethia (DTU)

13
2/18/2020

Basic Facts
•An unsafe state may lead to a deadlock.
•As long as the state is safe, the operating system can avoid unsafe (and
deadlocked) states.
•In an unsafe state, the operating system cannot prevent processes from
requesting resources such that a deadlock occurs: The behavior of the
processes controls unsafe states.

Resource-Allocation Graph Algorithm


Variant of Resource allocation graph for prevention can be used for avoidance if there
is one instance of each resource.
-Request and Assignment edges
-Addition claim edge.
•A claim edge Pi --->Rj indicated that process Pj may request resource Rj at some time
in the future; represented by a dashed line.

•Claim edge Pi -- Rj converts to request edge, when a process Pi requests a resource
Rj.

•When a resource Rj is released by a process Pi, assignment edge Rj Pi reconverts to a


claim edge Pi  Rj.

•And we must note that, resources must be claimed a priori in the system. (Before Pi
starts executing, all claim edges must appear in resource allocation graph. We can add
claim edge to process Pi if and only if all edges from Pi are claim edges

14
2/18/2020

Resource-Allocation Graph For Deadlock Avoidance


Request can be granted only if converting request edge Pi->Rj to assignment edge Rj->Pi
Does not form cycle in RA graph. Cycle detection in graph requires n square operations
If no cycles then system is safe
If there is a cycle expected Pi would need to wait eg: P2 is not allocated R2 since cycle is
formed

Divyashikha Sethia (DTU) 29

Banker’s Algorithm
The resource-allocation graph algorithm is not applicable to a resource-allocation
system with multiple instances of each resource type.
Banker’s algorithm:
- deadlock-avoidance algorithm is applicable to system with multiple resources but is
less efficient than the resource-allocation graph scheme.
Why called bankers algo: Algo could be used in banking system to make sure bank
never allocated its cash in such a way that it could always satisfy needs of customer.
a)Multiple instances of each resource type.

b)Each process must a priori claim maximum use which must be less than number of
system resources

c)When a process requests a resource it may have to wait since system would determine
if it will be in safe state.

d)When a process gets all its resources it must return them in a finite amount of time.

15
2/18/2020

Data Structures for the Banker’s Algorithm


n = number of processes, and m = number of resources types.

a) Available: Vector of length m indicates number of instances of a resource type.


available [j] = k, there are k instances of resource type Rj available.
a) Max: n x m matrix. If Max [i,j] = k, then process Pi may request at most k
instances of resource type Rj.
b) Allocation: n x m matrix. If Allocation[i,j] = k then Pi is currently allocated k
instances of Rj.
c) Need: n x m matrix. Indicates remaining resource need of process i.
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].

Vector notation used: X and Y vectors of length n X <= Y if for all I X[i] <= Y[i]
X =(1,7,3,2) Y=(0,3,2,1)

Safety Algorithm
Algorithm for finding out whether or not a system is in a safe state.
1. Let Work and Finish be vectors of length m and n, respectively. Initialize:
Work = Available
Finish [i] = false for i =0,1,2,3, …, n-1.
2. Find and 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.

5.Requires order of m x N sqaure operations to determine if state is safe

16
2/18/2020

Resource-Request Algorithm for Process Pi


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 the
process Pi, the following actions are taken:

1. If Requesti  Needi, go to step 2. Otherwise, raise error condition, since process


has exceeded its maximum claim.
2. If Requesti  Available, go to step 3. Otherwise Pi must wait, since resources are
not available.
3. Have the system pretend to have allocated requested resources to Pi by modifying
the state as follows:
Available = Available – Requesti ;
Allocationi = Allocationi + Requesti ;
Needi = Needi – Requesti;
 If the resulting state is 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


a) 5 processes P0 through P4; 3 resource types A (10 instances),
B (5instances, and C (7 instances).

b) Snapshot at time T0:


Allocation Max Available
ABC ABC ABC
P0 0 1 0 753 332
P1 2 0 0 322
P2 3 0 2 902
P3 2 1 1 222
P4 0 0 2 433

17
2/18/2020

Example (Cont.)
c) The content of the matrix. Need is defined to be Max
– Allocation.
Need
ABC
P0 7 4 3
P1 1 2 2
P2 6 0 0
P3 0 1 1
P4 4 3 1

d) The system is in a safe state since the sequence < P1,


P3, P4, P2, P0> satisfies safety criteria.

Example of Banker’s Algorithm


b) Snapshot at time T0:
Allocation Max Need Available
ABC ABC ABC ABC
P0 0 1 0 753 7 43 332
P1 2 0 0 322 122
P2 3 0 2 902 600
P3 2 1 1 222 011
P4 0 0 2 433 431

18
2/18/2020

Example P1 Request (1,0,2) (Cont.)


e) Check that Request1 (1 A and 2 C) made by P1  Available
(that is, (1,0,2)  (3,3,2)  true.

f) Assume Request has been fulfilled and new state arrived is:
( no actual allocation has been done just testing)
Allocation Need Available
ABC ABC ABC
P0 0 1 0 743 230
P1 3 0 2 020
P2 3 0 1 600
P3 2 1 1 011
P4 0 0 2 431

Example P1 Request (1,0,2) (Cont.)


g) Check if new system is safe:
Executing safety algorithm shows that sequence <P1, P3, P4,
P0, P2> satisfies safety requirement. => Grant request to P1

h) Now When system is in this state Avail = 2 3 0


Can request for (3,3,0) by P4 be granted?
No

i) Can request for (0,2,0) by P0 be granted?


Resulting state unsafe

19
2/18/2020

Deadlock Detection
If a system does not employ either a deadlock-prevention or a deadlock-
avoidance algorithm, then a deadlock situation may occur. In this
environment the system must provide :
• An algorithm that examines the state of the system to determine
whether a deadlock has occurred.
• An algorithm to recover from the deadlock.

Above requirements pertain to systems with single or 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 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.
In this method, we perform the following steps;
a) Maintain wait-for graph
– Nodes are processes.
– Pi  Pj if Pi is waiting for Pj.

b) Periodically, invoke an algorithm that searches for a cycle in the graph, because
if the wait-for graph contains a cycle, a deadlock exists in the system.

c) An algorithm to detect a cycle in a graph requires an order of n2 operations,


where n is the number of vertices in the graph.

20
2/18/2020

Resource-Allocation Graph and Wait-for Graph

Resource-Allocation Graph Corresponding wait-for graph

Divyashikha Sethia (DTU) 41

Several Instances of Resource Type


The wait-for graph scheme is not applicable to a resource-allocation system with
multiple instances of each resource type.

Deadlock-detection algorithm for several instance resource requires several time-


varying data structure that are similar to those used in the banker’s algorithm:

a)Available: A vector of length m indicates the number of available resources of each


type.

b)Allocation: An n x m matrix defines the number of resources of each type currently


allocated to each process.

c) Request: An n x m matrix indicates the current request of each process. If Request


[ij] = k, then process Pi is requesting k more instances of resource type. Rj.

21
2/18/2020

Detection Algorithm
The detection algorithm described here simply investigates every possible allocation
sequence for the processes that remain to be completed. The algorithm has the
following steps:

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


Work = Available. For i =1,2, …, n, if Allocationi  0,then Finish[i] =false;
otherwise, Finish[i] = true.

2. Find an index i such that both


– Finish[i] == false
– Requesti  Work
If no such i exists, go to step 4.

Detection Algorithm (Cont.)


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 deadlocked state.


Moreover, if Finish[i] == false, then Pi is deadlocked.

Step 3 assume Pi uses the Request(i) since it is <= Work and hence is not involved in a
deadlock . We assume optimistically that it will not require more resources and
will release the resources back hence Work is incremented by what had been
Allocated to process i
This algorithm requires an order of O(m x n2) operations to detect whether the
system is in deadlocked state.

22
2/18/2020

Example of Detection Algorithm


a) Five processes P0 through P4; three resource types
A (7 instances), B (2 instances), and C (6 instances).
b) Snapshot at time T0:
Allocation Request Available Work
ABC ABC ABC 000
P0 0 1 0 000 000 0 1 0 (i)
P1 2 0 0 202 7 2 4 (iv)
P2 3 0 3 000 3 1 3 (ii)
P3 2 1 1 100 5 2 4 (iii)
P4 0 0 2 002 7 2 6 (v)
c) Sequence <P0, P2, P3, P1, P4> will result in Finish[i] = true for all i.

Example (Cont.)
d) If P2 requests an additional instance of type C.
Allocation Request Available Work
ABC ABC ABC 000
P0 0 1 0 000 000 0 1 0 (i)
P1 2 0 0 202
P2 3 0 3 0 01
P3 2 1 1 100
P4 0 0 2 002

e) 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.

23
2/18/2020

Detection-Algorithm Usage
When should we invoke detection algorithm?
Two factors:
i) How often a deadlock is likely to occur?
ii) How many processes will be affected by deadlock when it happens?
• If deadlocks occur frequently:
- Detection algorithm should be invoked frequently.
- Resources allocated to deadlocked processes will be idle until deadlock can be
broken.
- Number of processes involved in the deadlock cycle may grow.

• If deadlock-detection algorithm is invoked for every resource request, this will


incur a considerable overhead in computation time.

Detection-Algorithm Usage…
• Deadlocks occur when a process makes request which cannot be granted.

• Could invoke deadlock detection every time resources cannot be allocated – can
identify deadlocked processes and processes that caused deadlock

• Inexpensive Alternative is simply to invoke the algorithm at less frequent intervals


(once per hour or when CPU until < 40%)

• If detection algorithm is invoked arbitrarily, there may be many cycles in resource


graph and so we would not be able to tell which of the many deadlocked processes
“caused” the deadlock.

24
2/18/2020

Recovery from Deadlock: Process Termination


How to eliminate deadlocks by aborting a process?
System must reclaim all resources allocated to the terminated processes.
a)Abort all deadlocked processes: This method clearly will break the deadlock cycle,
=>but at great expense.
b)Abort one process at a time until the deadlock cycle is terminated:
- Incurs considerable overhead, since after each process is aborted, a deadlock-
detection algorithm must invoked to determine whether any processes are still
deadlocked.
•Aborting process :
- Process middle of updating a file if aborted leaves file in incorrect state
•Now, we give some factors that affect which process is chosen to abort?
– Priority of the process.
– How long process has computed, and how much longer to completion.
– Resources the process has used.
– Resources process needs to complete.
– How many processes will need to be terminated.
– Is process interactive or batch?

Recovery from Deadlock: Resource Preemption


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.
Three important issues:
a) 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.
b) Rollback: if we preempt a resource from a process, what should be done with
that process?
Normal execution not possible since its needs resource.
=> Roll back process to some safe state and restart from that state.
If safe state cannot be determined then total rollback and restart process

c) Starvation: How do we ensure that starvation will not occur? That is, how can we
guarantee that resources will not always be preempted from the same process?
Possible that same process is selected for resource preemption
Cost factor to be used: Number of rollbacks for a process

25
2/18/2020

THANKS

26

Вам также может понравиться