1
Deadlocks (Galvin)
Outline
 SYSTEM MODEL
 DEADLOCK CHARACTERIZATION
o Necessary Conditions (Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait)
o Resource-Allocation Graph
 METHODS FOR HANDLING DEADLOCKS
 DEADLOCK PREVENTION
o Mutual Exclusion
o Hold and Wait
o No Pre-emption
o Circular Wait
 DEADLOCK AVOIDANCE
o Safe State
o Resource-Allocation Graph Algorithm
o Banker's Algorithm (Safety Algorithm, Resource-Request Algorithm/The Banker's Algorithm, An Illustrative Example)
 DEADLOCK DETECTION
o Single Instance of Each Resource Type
o Several Instances of a Resource Type
o Detection-Algorithm Usage
 RECOVERY FROMDEADLOCK
o Process Termination
o Resource Pre-emption (Selecting a victim, Rollback, Starvation)
Contents
In a multiprogrammingenvironment, several processesmaycompete for a finite number of resources. A processrequests resources;if the resources are
not available at that time, the process enters a waiting state. Sometimes, a waitingprocess is never againable to change state, because the resources it
has requestedare heldbyother waitingprocesses. Thissituationis called a deadlock.
Althoughsome applications canidentifyprograms that maydeadlock, operating systems typicallydonot provide dead lock-prevention facilities, and
it remains the responsibilityof programmers to ensure that theydesign deadlock-free programs.
SYSTEM MODEL
 A system consists of a finite number of resources to be distributedamong a number of competing processes. The resources maybe
partitioned into severaltypes (or classes), eachconsistingof some number of identical instances. CPU cycles, files, and I/O devices (such as
printers and DVD drives) are examples of resource types. If a systemhas two CPUs, then the resource type CPU has two instances. Similarly,
the resource type printer mayhave five instances. If a process requests an instance of a resource type, the allocationof anyinstance of the
type shouldsatisfythe request. For example, two printers maybe definedto be inthe same resource class ifno one cares whichprinter
prints whichoutput.
 Chapter 5 discussedvarious synchronizationtools, suchas mutex locks andsemaphores. These toolsare alsoconsideredsystem resources,
and theyare a commonsource of deadlock. However, a lock is typicallyassociatedwith protecting a specific data structure—that is, one lock
maybe used to protect accessto a queue, another to protect access to a linked list, and soforth. For that reason, eachlockis typically
assignedits ownresource class, anddefinitionis not a problem.
 A process must request a resource before using it andmust release the resource after using it. Under the normalmode of operation, a
process mayutilize a resource inonlythe following sequence: 1) Request 2) Use 3) Release
 The request andrelease of resources maybe system calls, as explainedin Chapter 2. Examples are the request() andrelease() device, open()
and close()file, andallocate() and free()memorysystemcalls. Similarly, as we saw inChapter 5, the request andrelease of semaphores can
be accomplishedthrough the wait() andsignal() operations on semaphores or through acquire() and release() of a mutex lock. For eachuse
2
Deadlocks (Galvin)
of a kernel-managedresource bya process or thread, the operating system checks to make sure that the processhas requestedandhas been
allocated the resource. A system table records whether eachresource is free or allocated. For eachresource that is allocated, the table also
records the process to which it is allocated. If a process requests a resource that is currentlyallocated to another process, it can be addedto
a queue of processes waitingfor this resource.
 A set of processes is in a deadlockedstate wheneveryprocess in the set is waiting for anevent that canbe causedonlybyanother process in
the set. A set of processes is ina deadlocked state when everyprocessinthe set is waitingfor anevent that canbe caused onlyby another
process inthe set. The resourcesmaybe either physical resources (for example, printers, tape drives, memoryspace, andCPU cycles)or
logical resources (for example, semaphores, mutex locks, andfiles). However, other types of events mayresult in deadlocks (for example, the
IPCfacilities discussedinChapter 3).
 To illustrate a deadlocked state, consider a system withthree CD RW drives. Suppose each ofthree processesholds one ofthese CDRW
drives. If each process now requests another drive, the three processes will be in a deadlockedstate. Each is waiting for th e event “CD RW is
released,” whichcanbe causedonlybyone of the other waitingprocesses. This example illustrates a deadlockinvolving the same resource
type. Deadlocks mayalsoinvolve different resource types. For example, consider a system withone printer andone DVD drive. Suppose that
process Pi is holdingthe DVD and process Pj is holding the printer. If Pi requests the printer andPj requests the DVDdrive, a deadlockoccurs.
 Developers of multithreaded applications must remainaware ofthe possibilityof deadlocks. The locking tools presentedinChapter 5 are
designedto avoidrace conditions. However, inusing these tools, developers must paycareful attentionto how locks are acquiredand
released. Otherwise, deadlockcanoccur, as illustrated inthe dining-philosophers problem in Section5.7.3.
Deadlock Characterization
In a deadlock, processes never finish executing, and system resources are tiedup, preventingother jobs fromstarting. Before we discussthe various
methods for dealingwith the deadlockproblem, we lookmore closelyat features that characterize deadlocks.
Necessary Conditions
 A deadlock situationcanarise ifthe followingfour conditions holdsimultaneouslyin a system:
o Mutual exclusion – At least one resource must be heldin a non-sharable mode; that is, onlyone process at a time canuse the
resource. If another process requests that resource, the requesting process must be delayeduntil the resource has beenreleased.
o Hold and wait – A process must be holding at least one resource andwaiting to acquire additional resources that are currentlybeing
heldbyother processes.
o No pre-emption – Resources cannot be preempted;that is, a resource canbe released onlyvoluntarilybythe process holding it,
after that processhas completedits task.
o Circular wait – A set {P0, P1, ..., Pn} of waiting processes must exist suchthat P0 is waiting for a resource heldbyP1, P1 is waiting for a
resource held byP2, ..., Pn−1 is waiting for a resource heldbyPn, andPn is waitingfor a resource heldbyP0.
 We emphasize that allfour conditions must holdfor a deadlock to occur. The circular-wait conditionimplies the hold-and-wait condition, so
the four conditions are not completelyindependent. We shall see inSection 7.4, however, that it is useful to consider eachcondition
separately.
Resource-Allocation Graph

3
Deadlocks (Galvin)

 Given the definitionof a resource-allocationgraph, it canbe shownthat, ifthe graphcontains nocycles, then noprocess in the system is
deadlocked. If the graph does containa cycle, then a deadlock MAY exist.
 If each resource type has exactlyone instance, thena cycle implies that a deadlockhas occurred. If the cycle involves only a set of resource
types, eachof which has onlya single instance, thena deadlockhas occurred. Eachprocessinvolvedinthe cycl e is deadlocked. Inthis case, a
cycle in the graphis botha necessaryanda sufficient condition for the existence of deadlock.
 If each resource type has severalinstances, thena cycle doesnot necessarilyimplythat a deadlock has
occurred. In this case, a cycle inthe graphis a necessarybut not a sufficient conditionfor the existence
of deadlock.
 To illustrate this concept, we returnto the resource-allocationgraphdepicted in Figure 7.1. Suppose
that process P3 requests an instance of resource type R2. Since noresource instance is currently
available, we add a request edge P3→ R2 to the graph(Figure 7.2). At this point, two minimal cycles exist
in the system:
P1 → R1 → P2 → R3 → P3 → R2 → P1
P2 → R3 → P3 → R2 → P2
Processes P1, P2, and P3 are deadlocked. ProcessP2 is waiting for the resource R3,
which is heldbyprocess P3. Process P3 is waitingfor either process P1 or processP2 to
release resource R2. Inaddition, processP1 is waiting for process P2 to release resource
R1.
Now consider the resource-allocationgraphinFigure 7.3. In this example, we also
have a cycle: P1 → R1 → P3 → R2 → P1
However, there is no deadlock. Observe that processP4 mayrelease its instance of
resource type R2. That resource canthen be allocatedto P3, breakingthe cycle.
In summary, if a resource-allocationgraphdoes not have a cycle, thenthe systemis
not in a deadlockedstate. If there is a cycle, then the system mayor maynot be ina deadlocked state. Thisobservationis important whenwe
deal withthe deadlock problem.
METHODS FOR HANDLING DEADLOCKS
We can deal withthe deadlockprobleminone of three ways:
 We can use a protocol to prevent or avoiddeadlocks, ensuringthat the systemwill never enter a deadlockedstate.
 We can allowthe system to enter a deadlockedstate, detect it, andrecover.
 We can ignore the problem altogether andpretendthat deadlocks never occur inthe system (andrestart manually).
The thirdsolution is the one usedbymost operating systems, including Linux andWindows.
Next, we elaborate brieflyon eachof the three methods for handling deadlocks. Then, inSections 7.4 through7.7, we present detailedalgorithms.
To ensure that deadlocks never occur, the system can useeither a deadlock preventionor a deadlock-avoidance scheme. Deadlock prevention provides
a set of methods to ensure that at least one ofthe four necessaryconditions cannot hold. These methods prevent deadlocks by constraining how
requests for resources canbe made.
Deadlock avoidance requires that the operatingsystem be givenadditional informationin advance concerning whichresourcesa process will
request and use duringits lifetime. Withthis additional knowledge, the operating system can decide for eachrequest whether or not the process should
wait. To decide whether the current request canbe satisfiedor must be delayed, the systemmust consider the resources curre ntlyavailable, the
resources currentlyallocatedto each process, and the future requests andreleases ofeachprocess.
If a systemdoesnot employeither a deadlock-preventionor a deadlockavoidance algorithm, thena deadlocksituationmayarise. In thisenvironment,
the systemcanprovide analgorithmthat examines the state of the system to determine whether a deadlock hasoccurred and analgorithm torecover
from the deadlock(ifa deadlockhas indeedoccurred). We discuss these issues inSection 7.6 and Section7.7.
4
Deadlocks (Galvin)
DEADLOCK PREVENTION
For a deadlock to occur, each ofthe four necessary conditions must hold. Byensuringthat at least one of these conditions cannot hold, we can
prevent the occurrence of a deadlock.
 Mutual Exclusion: In general, we cannot prevent deadlocks bydenyingthe mutual-exclusion condition, because some resources are
intrinsicallynonsharable. For example, a mutex lock cannot be simultaneouslysharedbyseveralprocesses. Sharable resources, incontrast, do
not require mutuallyexclusive access and thus cannot be involvedina deadlock. Read-onlyfilesare a goodexample of a sharable resource. If
several processesattempt to open a read-onlyfile at the same time, theycanbe granted simultaneous access to the file. A process never
needs to wait for a sharable resource.
 Hold and Wait: To ensure that the hold-and-wait conditionnever occurs in the system, we must guarantee that, whenever a process requests
a resource, it does not holdanyother resources. One protocol that we canuse requires eachprocess to request andbe allocated all its
resources before it begins execution. We canimplement this provision byrequiringthat systemcalls requesting resources for a process
precede all other systemcalls.
An alternative protocol allows a process to request resources onlywhenit hasnone. A process mayrequest some resources anduse them.
Before it canrequest anyadditional resources, it must release all the resources that it is currentlyallocated.
To illustrate the difference between these two protocols, we consider a process that copies data from a DVDdrive to a file ondisk, sorts the
file, andthen prints the results to a printer. Ifallresourcesmust be requestedat the beginningof the process, th enthe processmust initially
request the DVD drive, diskfile, andprinter. It will holdthe printer for its entire execution, even thoughit needs the printer onlyat the end.
The second method allows the processto request initiallyonlythe DVDdrive anddisk file. It copiesfrom the DVDdrive to the disk and then
releases both the DVDdrive andthe diskfile. The process must then request the disk file andthe printer. After copyingthe diskfile to the
printer, it releases these tworesources andterminates.
Both these protocols have twomain disadvantages. First, resource utilizationmaybe low, since resources maybe allocated but unused for
a long period. Second, starvationis possible. A process that needs several popular resources mayhave to wait indefinitely, because at least one
of the resources that it needs is always allocated to some other process.
 No Pre-emption: The thirdnecessaryconditionfor deadlocks is that there be no preemption of resources that have alreadybeenallocated. To
ensure that this condition does not hold, we can use the following protocol. If a process is holdingsome resources andrequests another
resource that cannot be immediatelyallocatedto it (that is, the processmust wait), thenallresources the process is currentlyholding are
preempted. In otherwords, these resources are implicitlyreleased. The preemptedresources are addedto the list of resources for whichthe
process is waiting. The process willbe restartedonlywhen it canregainits old resources, as well as the newonesthat it is requesting.
Alternatively, if a process requests some resources, we first checkwhether theyare available. If theyare, we allocate them. Iftheyare
not, we check whether theyare allocatedto some other process that is waiting for additional resources. If so, we preempt the desired
resources from the waitingprocessand allocate themto the requestingprocess. If the resources are neither available nor heldbya waiting
process, the requestingprocess must wait. While it is waiting, some of its resources maybe preempted, but onlyif another p rocessrequests
them. A process canbe restartedonlywhen it is allocated the newresourcesit is requesting andrecove rs anyresources that were preempted
while it was waiting.
This protocol is oftenapplied to resources whose state can be easilysavedand restoredlater, suchas CPU registers and memoryspace. It
cannot generallybe appliedto suchresourcesas mutex locks and semaphores.
 Circular Wait: The fourth and final conditionfor deadlocks is the circular-wait condition. One wayto ensure that this
conditionnever holds is to imposea total ordering of all resource types andto require that eachprocessrequests
resources inanincreasing order of enumeration. To illustrate, we let R = {R1, R2, ..., Rm} be the set of resource types.
We assignto eachresource type a unique integer number, which allows us to compare two
resources and to determine whether one precedes another inour ordering. Formally, we define
a one-to-one functionF:R→N, where N is the set of naturalnumbers. For example, if the set of
resource types R includes tape drives, disk drives, andprinters, thenthe functionF might be
definedas follows:
We can now consider the followingprotocol to prevent deadlocks:Each processcan
request resources onlyinan increasing order of enumeration. That is, a process can initially
request anynumber of instances of a resource type —say, Ri . After that, the process can
request instances ofresource type Rj if and onlyifF(Rj ) > F(Ri ). For example, using the function
definedpreviously, a process that wants to use the tape drive andprinter at the same time
must first request the tape drive andthenrequest the printer. Alternatively, we canrequire that
a process requesting aninstance of resource type Rj must have released anyresources Ri such
that F(Ri ) ≥ F(Rj ). Note alsothat if severalinstances ofthe same resource type are needed, a
single request for allof them must be issued. If these twoprotocols are used, thenthe circular-
wait conditioncannot hold. We candemonstrate this fact byassuming that a circular wait exists
(proof bycontradiction---SKIPPED).
We can accomplishthis scheme in an applicationprogram bydeveloping anorderingamong
all synchronizationobjects inthe system. All requests for synchronizationobjects must be made
in increasingorder. For example, if the lockordering in the Pthreadprogram shown in Figure 7.4
5
Deadlocks (Galvin)
was F(first mutex) = 1 and F(secondmutex) = 5 then thread twocouldnot request the locks out of order. Keep inmindthat developingan
ordering, or hierarchy, does not in itselfprevent deadlock. It is upto applicationdevelopers to write programs that follow the ordering. Also
note that the functionF should be defined according to the normalorder of usage of the resources in a system. For example, because the tape
drive is usuallyneededbefore the printer, it wouldbe reasonable to define F(tape drive)<F(printer).
Althoughensuring that resources are acquiredinthe proper order is the responsibilityof applicationdevelopers, certain software canbe
usedto verifythat locks are acquiredinthe proper order andto give appropriate warnings whenlocks are acquiredout of order anddeadlock
is possible. One lock-order verifier, whichworks on BSD versions of UNIXsuchas FreeBSD, is knownas witness. Witness uses mutual-exclusion
locks to protect critical sections, as describedinChapter 5. It works bydynamicallymaintaining the relationship oflock orders ina system. Let’s
use the program shown inFigure 7.4 as anexample. Assume that thread one is the first to acquire the locks anddoes sointh e order (1) first
_mutex, (2) second_mutex. Witness records the relationshipthat first mutex must be acquiredbefore secondmutex. Ifthread twolater
acquires the locks out of order, witness generates a warning message onthe systemconsole. It is also important to note that imposing a lock
ordering does not guarantee deadlockprevention if locks can be acquireddynamically (Rest of the content relevant, but SKIPPED at present,
including other code segment, and a short “Do it yourself” exercise).
DEADLOCK AVOIDANCE
As we saw, deadlock-prevention algorithms prevent deadlocks bylimitinghowrequests canbe made. The limits ensure that at least one of the necessary
conditions for deadlockcannot occur. Possible side effects of preventing deadlocks bythis method, however, are low device u tilizationandreduced
systemthroughput.
An alternative methodfor avoidingdeadlocks is to require additional information about how resources are to be requested. For example, in a system
with one tape drive andone printer, the systemmight needto know that process Pwill request first the tape drive and thenthe printer before releasing
both resources, whereasprocessQ will request first the printer andthen the tape drive. Withthis knowledge of the complete sequence ofrequests and
releases for each process, the system can decide for each request whether or not the processshould wait inorder to avoida possible future deadlock.
Each request requires that inmaking this decision the system consider the resources currentlyavailable, the resources curre ntlyallocated toeach
process, andthe future requests andreleasesof each process.
The various algorithms that use this approach differ in the amount andtype of information required. The simplest andmost useful modelrequires that
each process declare the maximumnumber ofresources ofeachtype that it mayneed. Giventhis a priori information, it is possible to construct an
algorithmthat ensures that the system will never enter a deadlocked state. A deadlock-avoidance algorithm dynamicallyexaminesthe resource-
allocationstate to ensure that a circular-wait conditioncannever exist. The resource allocation state is definedbythe number ofavailable andallocated
resources and the maximum demands ofthe processes. Inthe following sections, we explore two deadlock-avoidance algorithms.
Safe State
6
Deadlocks (Galvin)
Banker’s Algorithm
7
Deadlocks (Galvin)
DEADLOCK DETECTION
If a systemdoesnot employeither a deadlock-preventionor a deadlockavoidance algorithm, thena deadlocksituationmayoccur. Inthis environment,
the systemmayprovide:
 An algorithmthat examines the state of the systemto determine whether a deadlockhas occurred
 An algorithmto recover from the deadlock
In the followingdiscussion, we elaborate onthese two requirements as theypertainto systems withonlya single instance of eachresource type, as well
as to systems with several instancesof eachresource type. At this point, however,we note that a detection-and-recoveryscheme requiresoverheadthat
includes not onlythe run-time costs of maintaining the necessaryinformationandexecutingthe detection algorithm but alsothe potentiallosses
inherent in recoveringfrom a deadlock.
Single Instance of Each Resource Type
If all resources have onlya single instance, then we candefine a deadlock detectionalgorithmthat usesa variant of the resource-allocation graph, called
a wait-for graph. We obtainthisgraphfrom the resource-allocation graph by removing the resource nodes andcollapsing the appropriate edges. More
precisely, anedge from Pi to Pj in a wait-for graph implies that process Pi is waitingfor processPj to release a resource that Pi needs. An edge Pi → Pj
exists ina wait-for graphifandonlyif the correspondingresource allocationgraphcontains two edges Pi → Rq and Rq → Pj for some resource Rq . In
Figure 7.9, we present a resource-allocationgraphandthe correspondingwait-for graph.
As before, a deadlock exists inthe system if andonlyif the wait-for graphcontains a cycle. To detect deadlocks, the systemneeds to maintain the
wait for graphandperiodicallyinvoke analgorithm that searches for a cycle inthe graph. An algorithmto detect a cycle in a graphrequires an order of
n2 operations, where n is the number of vertices inthe graph.
Several Instances of a Resource Type
The wait-for graph scheme is not applicable to a resource-allocation system withmultiple instances ofeachresource type. We turn now to a deadlock
detection algorithm that is applicable to sucha system. The algorithm employs several time-varyingdata structures that are similar to those used inthe
banker’s algorithm:
• Available. A vector of length m indicates the number of available resources ofeachtype.
• Allocation. An n × m matrix defines the number of resources of each type currentlyallocated to each process.
• Request. An n × m matrix indicates the current request of each process. If Request[i][j] equals k, thenprocess Pi is requesting k more instances of
resource type Rj .
The ≤ relation betweentwo vectors is defined as in Section7.5.3. To simplifynotation, we again treat the rows in the matricesAllocationand Request as
vectors;we refer to them as Allocationi and Requesti . The detectionalgorithm describedhere simplyinvestigateseverypossible allocationsequence for
the processes that remainto be completed. Compare this algorithm withthe banker’s algorithm of Section7.5.3.
8
Deadlocks (Galvin)
Detection-Algorithm Usage
When should we invoke the detectionalgorithm? The answer depends ontwo factors:
 How oftenis a deadlock likelyto occur?
 How manyprocesses willbe affected bydeadlock when it happens?
If deadlocks occur frequently, then the detectionalgorithmshould be invokedfrequently. Resources allocated to deadlocked processeswill be idle until
the deadlock canbe broken. Inaddition, the number of processes involvedinthe deadlock cycle maygrow.
Deadlocks occur onlywhensome process makesa request that cannot be grantedimmediately. This request maybe the final request that completes a
chainof waitingprocesses. Inthe extreme, then, we caninvoke the deadlock detectionalgorithmeverytime a request for allocationcannot be gra nted
immediately. In thiscase, we can identifynot onlythe deadlocked set of processesbut alsothe specific process that “caused” the deadlock. (In reality,
each of the deadlocked processesis a linkinthe cycle in the resource graph, so all ofthem, jointly, causedthe deadlock.)If there are manydifferent
resource types, one request maycreate manycycles inthe resource graph, eachcycle completedbythe most recent request and “caused” bythe one
identifiable process.
Of course, invokingthe deadlock-detectionalgorithm for everyresource request willincur considerable overhead in computationtime. A lessexpensive
alternative is simplyto invoke the algorithmat definedintervals—for example, once per hour or whenever CPU utilizationdrops below40 percent. (A
deadlock eventuallycripples systemthroughput andcauses CPU utilizationto drop.) Ifthe detection algorithm is invokedat arbitrarypoints in time, the
resource graph maycontainmanycycles. Inthiscase, we generallycannot tell whichof the manydeadlockedprocesses “caused” the deadlock.
RECOVERY FROMDEADLOCK
When a detectionalgorithmdetermines that a deadlock exists, severalalternatives are available. One possibilityis to informthe operator that a
deadlock hasoccurred and to let the operator deal withthe deadlock manually. Another possibilityis to let the systemrecove r fromthe deadlock
automatically. There are two options for breaking a deadlock. One is simplyto abort one or more processes to b reakthe circular wait. The other is to
preempt some resources fromone or more ofthe deadlockedprocesses.
Process Termination
To eliminate deadlocks byaborting a process, we use one of two methods. In bothmethods, the system reclaims all resources allocated to the
terminatedprocesses.
 Abort all deadlocked processes. This methodclearlywill break the deadlockcycle, but at great expense. The deadlockedprocesses mayhave
computedfor a long time, andthe results ofthese partial computations must be discarded andprobablywill have to be recomputed later.
 Abort one process at a time until the deadlock cycle is eliminated. This methodincurs considerable overhead, since after eachprocess is
aborted, a deadlock-detectionalgorithm must be invokedto determine whether anyprocesses are still deadlocked.
Aborting a process maynot be easy. If the process was inthe midst of updatinga file, terminating it will leave that file in anincorrect state. Similarly, if
the processwas in the midst of printing data on a printer, the system must reset the printer to a correct state before printingthe next job. Ifthe partial
termination methodis used, then we must determine which deadlockedprocess (or processes) shouldbe terminated. Thisdeterminationis a policy
decision, similar to CPU-schedulingdecisions. The questionis basicallyaneconomic one; we should abort those processes whose terminationwill incur
the minimum cost. Unfortunately, the term minimumcost is not a precise one. Manyfactors mayaffect whichprocessis chosen, including:
1. What the priorityof the process is
2. How long the process hascomputedandhowmuchl onger the process will compute before completing its designatedtask
3. How manyandwhat types of resources the process has used(for example, whether the resources are simple to preempt)
4. How manymore resources the process needs inorder to complete
5. How manyprocesseswill needto be terminated6. Whether the process is interactive or batch
Resource Preemption
To eliminate deadlocks using resource preemption, we successivelypreempt some resources from processes andgive these resources to other processes
until the deadlock cycle is broken. If preemptionis requiredto deal withdeadlocks, then three issues needto be addressed:
 Selecting a victim. Which resources andwhich processes are to be preempted?As inprocesstermination, we must determine the order of
preemption to minimize cost. Cost factors mayinclude suchparameters as the number of resources a deadlockedprocessis holding and the
amount of time the process has thus far consumed.
 Rollback. If we preempt a resource from a process, what shouldbe done withthat process?Clearly, it cannot continue withits normal
execution;it is missing some neededresource. We must roll backthe process to some safe state andrestart it from that state. Since, in
general, it is difficult to determine what a safe state is, the simplest solutionis a total rollback:abort the process andthenrestart it. Althoughit
is more effective to roll back the process onlyas far as necessaryto breakthe deadlock, thismethodrequires the system to keepmore
informationabout the state ofallrunning processes.
 Starvation. How do we ensure that starvation will not occur? That is, howcanwe guarantee that resources will not always be preemptedfrom
the same process?
In a system where victim selection is basedprimarilyon cost factors, it mayhappenthat the same process is always pickedas a victim. As a result, this
process never completesits designatedtask, a starvationsituation anypractical systemmust address. Clearly, we must ensure that a processcanbe
pickedas a victim onlya (small)finite number of times. The most common solutionis to include the number of rollbacks inthe cost factor.
9
Deadlocks (Galvin)
SUMMARY
A deadlockedstate occurs whentwo or more processes are waiting indefinitelyfor anevent that canbe causedonlybyone of the waiting processes.
There are three principal methods for dealing withdeadlocks:
 Use some protocol to prevent or avoiddeadlocks, ensuringthat the systemwill never enter a deadlockedstate.
 Allowthe system to enter a deadlockedstate, detect it, andthenrecover.
 Ignore the problem altogether andpretendthat deadlocks never occur inthe system.
The thirdsolution is the one usedbymost operating systems, including Linux andWindows.
A deadlock canoccur onlyif four necessaryconditions holdsimultaneouslyinthe system:mutual exclusion, holdandwait, no p reemption, andcircular
wait. To prevent deadlocks, we canensure that at least one of the necessaryconditions never holds.
A method for avoiding deadlocks, rather thanpreventing them, requires that the operating system have a priori informationabout how eachprocess
will utilize system resources. The banker’s algorithm, for example, requires a priori informationabout the maximum number of eachresource class that
each process mayrequest. Using this information, we candefine a deadlock avoidance algorithm.
If a system does not employa protocol to ensure that deadlocks will never occur, then a detection-and-recoveryscheme maybe employed. A deadlock
detection algorithm must be invokedto determine whether a deadlock has occurred. If a deadlock is detected, the systemmust recover either by
terminatingsome ofthe deadlockedprocesses or bypreemptingresources from some of the deadlockedprocesses.
Where preemption is used to dealwith deadlocks, three issues must be addressed:selectinga victim, rollback, and starvation . In a systemthat selects
victims for rollback primarilyonthe basisof cost factors, starvationmayoccur, andthe selectedprocess cannever complete its designated task.
Researchers have arguedthat none of the basic approachesalone is appropriate for the entire spectrum ofresource-allocationproblems inoperating
systems. The basic approaches can be combined, however, allowing us to select an optimal approach for eachclass of resources in a system.
AssortedContent
 XXX
To be cleared
 I
Q’s Later
 XXX
Glossary
ReadLater
Further Reading
 S

Grey Areas
 XXX

Deadlocks prefinal

  • 1.
    1 Deadlocks (Galvin) Outline  SYSTEMMODEL  DEADLOCK CHARACTERIZATION o Necessary Conditions (Mutual Exclusion, Hold and Wait, No Preemption, Circular Wait) o Resource-Allocation Graph  METHODS FOR HANDLING DEADLOCKS  DEADLOCK PREVENTION o Mutual Exclusion o Hold and Wait o No Pre-emption o Circular Wait  DEADLOCK AVOIDANCE o Safe State o Resource-Allocation Graph Algorithm o Banker's Algorithm (Safety Algorithm, Resource-Request Algorithm/The Banker's Algorithm, An Illustrative Example)  DEADLOCK DETECTION o Single Instance of Each Resource Type o Several Instances of a Resource Type o Detection-Algorithm Usage  RECOVERY FROMDEADLOCK o Process Termination o Resource Pre-emption (Selecting a victim, Rollback, Starvation) Contents In a multiprogrammingenvironment, several processesmaycompete for a finite number of resources. A processrequests resources;if the resources are not available at that time, the process enters a waiting state. Sometimes, a waitingprocess is never againable to change state, because the resources it has requestedare heldbyother waitingprocesses. Thissituationis called a deadlock. Althoughsome applications canidentifyprograms that maydeadlock, operating systems typicallydonot provide dead lock-prevention facilities, and it remains the responsibilityof programmers to ensure that theydesign deadlock-free programs. SYSTEM MODEL  A system consists of a finite number of resources to be distributedamong a number of competing processes. The resources maybe partitioned into severaltypes (or classes), eachconsistingof some number of identical instances. CPU cycles, files, and I/O devices (such as printers and DVD drives) are examples of resource types. If a systemhas two CPUs, then the resource type CPU has two instances. Similarly, the resource type printer mayhave five instances. If a process requests an instance of a resource type, the allocationof anyinstance of the type shouldsatisfythe request. For example, two printers maybe definedto be inthe same resource class ifno one cares whichprinter prints whichoutput.  Chapter 5 discussedvarious synchronizationtools, suchas mutex locks andsemaphores. These toolsare alsoconsideredsystem resources, and theyare a commonsource of deadlock. However, a lock is typicallyassociatedwith protecting a specific data structure—that is, one lock maybe used to protect accessto a queue, another to protect access to a linked list, and soforth. For that reason, eachlockis typically assignedits ownresource class, anddefinitionis not a problem.  A process must request a resource before using it andmust release the resource after using it. Under the normalmode of operation, a process mayutilize a resource inonlythe following sequence: 1) Request 2) Use 3) Release  The request andrelease of resources maybe system calls, as explainedin Chapter 2. Examples are the request() andrelease() device, open() and close()file, andallocate() and free()memorysystemcalls. Similarly, as we saw inChapter 5, the request andrelease of semaphores can be accomplishedthrough the wait() andsignal() operations on semaphores or through acquire() and release() of a mutex lock. For eachuse
  • 2.
    2 Deadlocks (Galvin) of akernel-managedresource bya process or thread, the operating system checks to make sure that the processhas requestedandhas been allocated the resource. A system table records whether eachresource is free or allocated. For eachresource that is allocated, the table also records the process to which it is allocated. If a process requests a resource that is currentlyallocated to another process, it can be addedto a queue of processes waitingfor this resource.  A set of processes is in a deadlockedstate wheneveryprocess in the set is waiting for anevent that canbe causedonlybyanother process in the set. A set of processes is ina deadlocked state when everyprocessinthe set is waitingfor anevent that canbe caused onlyby another process inthe set. The resourcesmaybe either physical resources (for example, printers, tape drives, memoryspace, andCPU cycles)or logical resources (for example, semaphores, mutex locks, andfiles). However, other types of events mayresult in deadlocks (for example, the IPCfacilities discussedinChapter 3).  To illustrate a deadlocked state, consider a system withthree CD RW drives. Suppose each ofthree processesholds one ofthese CDRW drives. If each process now requests another drive, the three processes will be in a deadlockedstate. Each is waiting for th e event “CD RW is released,” whichcanbe causedonlybyone of the other waitingprocesses. This example illustrates a deadlockinvolving the same resource type. Deadlocks mayalsoinvolve different resource types. For example, consider a system withone printer andone DVD drive. Suppose that process Pi is holdingthe DVD and process Pj is holding the printer. If Pi requests the printer andPj requests the DVDdrive, a deadlockoccurs.  Developers of multithreaded applications must remainaware ofthe possibilityof deadlocks. The locking tools presentedinChapter 5 are designedto avoidrace conditions. However, inusing these tools, developers must paycareful attentionto how locks are acquiredand released. Otherwise, deadlockcanoccur, as illustrated inthe dining-philosophers problem in Section5.7.3. Deadlock Characterization In a deadlock, processes never finish executing, and system resources are tiedup, preventingother jobs fromstarting. Before we discussthe various methods for dealingwith the deadlockproblem, we lookmore closelyat features that characterize deadlocks. Necessary Conditions  A deadlock situationcanarise ifthe followingfour conditions holdsimultaneouslyin a system: o Mutual exclusion – At least one resource must be heldin a non-sharable mode; that is, onlyone process at a time canuse the resource. If another process requests that resource, the requesting process must be delayeduntil the resource has beenreleased. o Hold and wait – A process must be holding at least one resource andwaiting to acquire additional resources that are currentlybeing heldbyother processes. o No pre-emption – Resources cannot be preempted;that is, a resource canbe released onlyvoluntarilybythe process holding it, after that processhas completedits task. o Circular wait – A set {P0, P1, ..., Pn} of waiting processes must exist suchthat P0 is waiting for a resource heldbyP1, P1 is waiting for a resource held byP2, ..., Pn−1 is waiting for a resource heldbyPn, andPn is waitingfor a resource heldbyP0.  We emphasize that allfour conditions must holdfor a deadlock to occur. The circular-wait conditionimplies the hold-and-wait condition, so the four conditions are not completelyindependent. We shall see inSection 7.4, however, that it is useful to consider eachcondition separately. Resource-Allocation Graph 
  • 3.
    3 Deadlocks (Galvin)   Giventhe definitionof a resource-allocationgraph, it canbe shownthat, ifthe graphcontains nocycles, then noprocess in the system is deadlocked. If the graph does containa cycle, then a deadlock MAY exist.  If each resource type has exactlyone instance, thena cycle implies that a deadlockhas occurred. If the cycle involves only a set of resource types, eachof which has onlya single instance, thena deadlockhas occurred. Eachprocessinvolvedinthe cycl e is deadlocked. Inthis case, a cycle in the graphis botha necessaryanda sufficient condition for the existence of deadlock.  If each resource type has severalinstances, thena cycle doesnot necessarilyimplythat a deadlock has occurred. In this case, a cycle inthe graphis a necessarybut not a sufficient conditionfor the existence of deadlock.  To illustrate this concept, we returnto the resource-allocationgraphdepicted in Figure 7.1. Suppose that process P3 requests an instance of resource type R2. Since noresource instance is currently available, we add a request edge P3→ R2 to the graph(Figure 7.2). At this point, two minimal cycles exist in the system: P1 → R1 → P2 → R3 → P3 → R2 → P1 P2 → R3 → P3 → R2 → P2 Processes P1, P2, and P3 are deadlocked. ProcessP2 is waiting for the resource R3, which is heldbyprocess P3. Process P3 is waitingfor either process P1 or processP2 to release resource R2. Inaddition, processP1 is waiting for process P2 to release resource R1. Now consider the resource-allocationgraphinFigure 7.3. In this example, we also have a cycle: P1 → R1 → P3 → R2 → P1 However, there is no deadlock. Observe that processP4 mayrelease its instance of resource type R2. That resource canthen be allocatedto P3, breakingthe cycle. In summary, if a resource-allocationgraphdoes not have a cycle, thenthe systemis not in a deadlockedstate. If there is a cycle, then the system mayor maynot be ina deadlocked state. Thisobservationis important whenwe deal withthe deadlock problem. METHODS FOR HANDLING DEADLOCKS We can deal withthe deadlockprobleminone of three ways:  We can use a protocol to prevent or avoiddeadlocks, ensuringthat the systemwill never enter a deadlockedstate.  We can allowthe system to enter a deadlockedstate, detect it, andrecover.  We can ignore the problem altogether andpretendthat deadlocks never occur inthe system (andrestart manually). The thirdsolution is the one usedbymost operating systems, including Linux andWindows. Next, we elaborate brieflyon eachof the three methods for handling deadlocks. Then, inSections 7.4 through7.7, we present detailedalgorithms. To ensure that deadlocks never occur, the system can useeither a deadlock preventionor a deadlock-avoidance scheme. Deadlock prevention provides a set of methods to ensure that at least one ofthe four necessaryconditions cannot hold. These methods prevent deadlocks by constraining how requests for resources canbe made. Deadlock avoidance requires that the operatingsystem be givenadditional informationin advance concerning whichresourcesa process will request and use duringits lifetime. Withthis additional knowledge, the operating system can decide for eachrequest whether or not the process should wait. To decide whether the current request canbe satisfiedor must be delayed, the systemmust consider the resources curre ntlyavailable, the resources currentlyallocatedto each process, and the future requests andreleases ofeachprocess. If a systemdoesnot employeither a deadlock-preventionor a deadlockavoidance algorithm, thena deadlocksituationmayarise. In thisenvironment, the systemcanprovide analgorithmthat examines the state of the system to determine whether a deadlock hasoccurred and analgorithm torecover from the deadlock(ifa deadlockhas indeedoccurred). We discuss these issues inSection 7.6 and Section7.7.
  • 4.
    4 Deadlocks (Galvin) DEADLOCK PREVENTION Fora deadlock to occur, each ofthe four necessary conditions must hold. Byensuringthat at least one of these conditions cannot hold, we can prevent the occurrence of a deadlock.  Mutual Exclusion: In general, we cannot prevent deadlocks bydenyingthe mutual-exclusion condition, because some resources are intrinsicallynonsharable. For example, a mutex lock cannot be simultaneouslysharedbyseveralprocesses. Sharable resources, incontrast, do not require mutuallyexclusive access and thus cannot be involvedina deadlock. Read-onlyfilesare a goodexample of a sharable resource. If several processesattempt to open a read-onlyfile at the same time, theycanbe granted simultaneous access to the file. A process never needs to wait for a sharable resource.  Hold and Wait: To ensure that the hold-and-wait conditionnever occurs in the system, we must guarantee that, whenever a process requests a resource, it does not holdanyother resources. One protocol that we canuse requires eachprocess to request andbe allocated all its resources before it begins execution. We canimplement this provision byrequiringthat systemcalls requesting resources for a process precede all other systemcalls. An alternative protocol allows a process to request resources onlywhenit hasnone. A process mayrequest some resources anduse them. Before it canrequest anyadditional resources, it must release all the resources that it is currentlyallocated. To illustrate the difference between these two protocols, we consider a process that copies data from a DVDdrive to a file ondisk, sorts the file, andthen prints the results to a printer. Ifallresourcesmust be requestedat the beginningof the process, th enthe processmust initially request the DVD drive, diskfile, andprinter. It will holdthe printer for its entire execution, even thoughit needs the printer onlyat the end. The second method allows the processto request initiallyonlythe DVDdrive anddisk file. It copiesfrom the DVDdrive to the disk and then releases both the DVDdrive andthe diskfile. The process must then request the disk file andthe printer. After copyingthe diskfile to the printer, it releases these tworesources andterminates. Both these protocols have twomain disadvantages. First, resource utilizationmaybe low, since resources maybe allocated but unused for a long period. Second, starvationis possible. A process that needs several popular resources mayhave to wait indefinitely, because at least one of the resources that it needs is always allocated to some other process.  No Pre-emption: The thirdnecessaryconditionfor deadlocks is that there be no preemption of resources that have alreadybeenallocated. To ensure that this condition does not hold, we can use the following protocol. If a process is holdingsome resources andrequests another resource that cannot be immediatelyallocatedto it (that is, the processmust wait), thenallresources the process is currentlyholding are preempted. In otherwords, these resources are implicitlyreleased. The preemptedresources are addedto the list of resources for whichthe process is waiting. The process willbe restartedonlywhen it canregainits old resources, as well as the newonesthat it is requesting. Alternatively, if a process requests some resources, we first checkwhether theyare available. If theyare, we allocate them. Iftheyare not, we check whether theyare allocatedto some other process that is waiting for additional resources. If so, we preempt the desired resources from the waitingprocessand allocate themto the requestingprocess. If the resources are neither available nor heldbya waiting process, the requestingprocess must wait. While it is waiting, some of its resources maybe preempted, but onlyif another p rocessrequests them. A process canbe restartedonlywhen it is allocated the newresourcesit is requesting andrecove rs anyresources that were preempted while it was waiting. This protocol is oftenapplied to resources whose state can be easilysavedand restoredlater, suchas CPU registers and memoryspace. It cannot generallybe appliedto suchresourcesas mutex locks and semaphores.  Circular Wait: The fourth and final conditionfor deadlocks is the circular-wait condition. One wayto ensure that this conditionnever holds is to imposea total ordering of all resource types andto require that eachprocessrequests resources inanincreasing order of enumeration. To illustrate, we let R = {R1, R2, ..., Rm} be the set of resource types. We assignto eachresource type a unique integer number, which allows us to compare two resources and to determine whether one precedes another inour ordering. Formally, we define a one-to-one functionF:R→N, where N is the set of naturalnumbers. For example, if the set of resource types R includes tape drives, disk drives, andprinters, thenthe functionF might be definedas follows: We can now consider the followingprotocol to prevent deadlocks:Each processcan request resources onlyinan increasing order of enumeration. That is, a process can initially request anynumber of instances of a resource type —say, Ri . After that, the process can request instances ofresource type Rj if and onlyifF(Rj ) > F(Ri ). For example, using the function definedpreviously, a process that wants to use the tape drive andprinter at the same time must first request the tape drive andthenrequest the printer. Alternatively, we canrequire that a process requesting aninstance of resource type Rj must have released anyresources Ri such that F(Ri ) ≥ F(Rj ). Note alsothat if severalinstances ofthe same resource type are needed, a single request for allof them must be issued. If these twoprotocols are used, thenthe circular- wait conditioncannot hold. We candemonstrate this fact byassuming that a circular wait exists (proof bycontradiction---SKIPPED). We can accomplishthis scheme in an applicationprogram bydeveloping anorderingamong all synchronizationobjects inthe system. All requests for synchronizationobjects must be made in increasingorder. For example, if the lockordering in the Pthreadprogram shown in Figure 7.4
  • 5.
    5 Deadlocks (Galvin) was F(firstmutex) = 1 and F(secondmutex) = 5 then thread twocouldnot request the locks out of order. Keep inmindthat developingan ordering, or hierarchy, does not in itselfprevent deadlock. It is upto applicationdevelopers to write programs that follow the ordering. Also note that the functionF should be defined according to the normalorder of usage of the resources in a system. For example, because the tape drive is usuallyneededbefore the printer, it wouldbe reasonable to define F(tape drive)<F(printer). Althoughensuring that resources are acquiredinthe proper order is the responsibilityof applicationdevelopers, certain software canbe usedto verifythat locks are acquiredinthe proper order andto give appropriate warnings whenlocks are acquiredout of order anddeadlock is possible. One lock-order verifier, whichworks on BSD versions of UNIXsuchas FreeBSD, is knownas witness. Witness uses mutual-exclusion locks to protect critical sections, as describedinChapter 5. It works bydynamicallymaintaining the relationship oflock orders ina system. Let’s use the program shown inFigure 7.4 as anexample. Assume that thread one is the first to acquire the locks anddoes sointh e order (1) first _mutex, (2) second_mutex. Witness records the relationshipthat first mutex must be acquiredbefore secondmutex. Ifthread twolater acquires the locks out of order, witness generates a warning message onthe systemconsole. It is also important to note that imposing a lock ordering does not guarantee deadlockprevention if locks can be acquireddynamically (Rest of the content relevant, but SKIPPED at present, including other code segment, and a short “Do it yourself” exercise). DEADLOCK AVOIDANCE As we saw, deadlock-prevention algorithms prevent deadlocks bylimitinghowrequests canbe made. The limits ensure that at least one of the necessary conditions for deadlockcannot occur. Possible side effects of preventing deadlocks bythis method, however, are low device u tilizationandreduced systemthroughput. An alternative methodfor avoidingdeadlocks is to require additional information about how resources are to be requested. For example, in a system with one tape drive andone printer, the systemmight needto know that process Pwill request first the tape drive and thenthe printer before releasing both resources, whereasprocessQ will request first the printer andthen the tape drive. Withthis knowledge of the complete sequence ofrequests and releases for each process, the system can decide for each request whether or not the processshould wait inorder to avoida possible future deadlock. Each request requires that inmaking this decision the system consider the resources currentlyavailable, the resources curre ntlyallocated toeach process, andthe future requests andreleasesof each process. The various algorithms that use this approach differ in the amount andtype of information required. The simplest andmost useful modelrequires that each process declare the maximumnumber ofresources ofeachtype that it mayneed. Giventhis a priori information, it is possible to construct an algorithmthat ensures that the system will never enter a deadlocked state. A deadlock-avoidance algorithm dynamicallyexaminesthe resource- allocationstate to ensure that a circular-wait conditioncannever exist. The resource allocation state is definedbythe number ofavailable andallocated resources and the maximum demands ofthe processes. Inthe following sections, we explore two deadlock-avoidance algorithms. Safe State
  • 6.
  • 7.
    7 Deadlocks (Galvin) DEADLOCK DETECTION Ifa systemdoesnot employeither a deadlock-preventionor a deadlockavoidance algorithm, thena deadlocksituationmayoccur. Inthis environment, the systemmayprovide:  An algorithmthat examines the state of the systemto determine whether a deadlockhas occurred  An algorithmto recover from the deadlock In the followingdiscussion, we elaborate onthese two requirements as theypertainto systems withonlya single instance of eachresource type, as well as to systems with several instancesof eachresource type. At this point, however,we note that a detection-and-recoveryscheme requiresoverheadthat includes not onlythe run-time costs of maintaining the necessaryinformationandexecutingthe detection algorithm but alsothe potentiallosses inherent in recoveringfrom a deadlock. Single Instance of Each Resource Type If all resources have onlya single instance, then we candefine a deadlock detectionalgorithmthat usesa variant of the resource-allocation graph, called a wait-for graph. We obtainthisgraphfrom the resource-allocation graph by removing the resource nodes andcollapsing the appropriate edges. More precisely, anedge from Pi to Pj in a wait-for graph implies that process Pi is waitingfor processPj to release a resource that Pi needs. An edge Pi → Pj exists ina wait-for graphifandonlyif the correspondingresource allocationgraphcontains two edges Pi → Rq and Rq → Pj for some resource Rq . In Figure 7.9, we present a resource-allocationgraphandthe correspondingwait-for graph. As before, a deadlock exists inthe system if andonlyif the wait-for graphcontains a cycle. To detect deadlocks, the systemneeds to maintain the wait for graphandperiodicallyinvoke analgorithm that searches for a cycle inthe graph. An algorithmto detect a cycle in a graphrequires an order of n2 operations, where n is the number of vertices inthe graph. Several Instances of a Resource Type The wait-for graph scheme is not applicable to a resource-allocation system withmultiple instances ofeachresource type. We turn now to a deadlock detection algorithm that is applicable to sucha system. The algorithm employs several time-varyingdata structures that are similar to those used inthe banker’s algorithm: • Available. A vector of length m indicates the number of available resources ofeachtype. • Allocation. An n × m matrix defines the number of resources of each type currentlyallocated to each process. • Request. An n × m matrix indicates the current request of each process. If Request[i][j] equals k, thenprocess Pi is requesting k more instances of resource type Rj . The ≤ relation betweentwo vectors is defined as in Section7.5.3. To simplifynotation, we again treat the rows in the matricesAllocationand Request as vectors;we refer to them as Allocationi and Requesti . The detectionalgorithm describedhere simplyinvestigateseverypossible allocationsequence for the processes that remainto be completed. Compare this algorithm withthe banker’s algorithm of Section7.5.3.
  • 8.
    8 Deadlocks (Galvin) Detection-Algorithm Usage Whenshould we invoke the detectionalgorithm? The answer depends ontwo factors:  How oftenis a deadlock likelyto occur?  How manyprocesses willbe affected bydeadlock when it happens? If deadlocks occur frequently, then the detectionalgorithmshould be invokedfrequently. Resources allocated to deadlocked processeswill be idle until the deadlock canbe broken. Inaddition, the number of processes involvedinthe deadlock cycle maygrow. Deadlocks occur onlywhensome process makesa request that cannot be grantedimmediately. This request maybe the final request that completes a chainof waitingprocesses. Inthe extreme, then, we caninvoke the deadlock detectionalgorithmeverytime a request for allocationcannot be gra nted immediately. In thiscase, we can identifynot onlythe deadlocked set of processesbut alsothe specific process that “caused” the deadlock. (In reality, each of the deadlocked processesis a linkinthe cycle in the resource graph, so all ofthem, jointly, causedthe deadlock.)If there are manydifferent resource types, one request maycreate manycycles inthe resource graph, eachcycle completedbythe most recent request and “caused” bythe one identifiable process. Of course, invokingthe deadlock-detectionalgorithm for everyresource request willincur considerable overhead in computationtime. A lessexpensive alternative is simplyto invoke the algorithmat definedintervals—for example, once per hour or whenever CPU utilizationdrops below40 percent. (A deadlock eventuallycripples systemthroughput andcauses CPU utilizationto drop.) Ifthe detection algorithm is invokedat arbitrarypoints in time, the resource graph maycontainmanycycles. Inthiscase, we generallycannot tell whichof the manydeadlockedprocesses “caused” the deadlock. RECOVERY FROMDEADLOCK When a detectionalgorithmdetermines that a deadlock exists, severalalternatives are available. One possibilityis to informthe operator that a deadlock hasoccurred and to let the operator deal withthe deadlock manually. Another possibilityis to let the systemrecove r fromthe deadlock automatically. There are two options for breaking a deadlock. One is simplyto abort one or more processes to b reakthe circular wait. The other is to preempt some resources fromone or more ofthe deadlockedprocesses. Process Termination To eliminate deadlocks byaborting a process, we use one of two methods. In bothmethods, the system reclaims all resources allocated to the terminatedprocesses.  Abort all deadlocked processes. This methodclearlywill break the deadlockcycle, but at great expense. The deadlockedprocesses mayhave computedfor a long time, andthe results ofthese partial computations must be discarded andprobablywill have to be recomputed later.  Abort one process at a time until the deadlock cycle is eliminated. This methodincurs considerable overhead, since after eachprocess is aborted, a deadlock-detectionalgorithm must be invokedto determine whether anyprocesses are still deadlocked. Aborting a process maynot be easy. If the process was inthe midst of updatinga file, terminating it will leave that file in anincorrect state. Similarly, if the processwas in the midst of printing data on a printer, the system must reset the printer to a correct state before printingthe next job. Ifthe partial termination methodis used, then we must determine which deadlockedprocess (or processes) shouldbe terminated. Thisdeterminationis a policy decision, similar to CPU-schedulingdecisions. The questionis basicallyaneconomic one; we should abort those processes whose terminationwill incur the minimum cost. Unfortunately, the term minimumcost is not a precise one. Manyfactors mayaffect whichprocessis chosen, including: 1. What the priorityof the process is 2. How long the process hascomputedandhowmuchl onger the process will compute before completing its designatedtask 3. How manyandwhat types of resources the process has used(for example, whether the resources are simple to preempt) 4. How manymore resources the process needs inorder to complete 5. How manyprocesseswill needto be terminated6. Whether the process is interactive or batch Resource Preemption To eliminate deadlocks using resource preemption, we successivelypreempt some resources from processes andgive these resources to other processes until the deadlock cycle is broken. If preemptionis requiredto deal withdeadlocks, then three issues needto be addressed:  Selecting a victim. Which resources andwhich processes are to be preempted?As inprocesstermination, we must determine the order of preemption to minimize cost. Cost factors mayinclude suchparameters as the number of resources a deadlockedprocessis holding and the amount of time the process has thus far consumed.  Rollback. If we preempt a resource from a process, what shouldbe done withthat process?Clearly, it cannot continue withits normal execution;it is missing some neededresource. We must roll backthe process to some safe state andrestart it from that state. Since, in general, it is difficult to determine what a safe state is, the simplest solutionis a total rollback:abort the process andthenrestart it. Althoughit is more effective to roll back the process onlyas far as necessaryto breakthe deadlock, thismethodrequires the system to keepmore informationabout the state ofallrunning processes.  Starvation. How do we ensure that starvation will not occur? That is, howcanwe guarantee that resources will not always be preemptedfrom the same process? In a system where victim selection is basedprimarilyon cost factors, it mayhappenthat the same process is always pickedas a victim. As a result, this process never completesits designatedtask, a starvationsituation anypractical systemmust address. Clearly, we must ensure that a processcanbe pickedas a victim onlya (small)finite number of times. The most common solutionis to include the number of rollbacks inthe cost factor.
  • 9.
    9 Deadlocks (Galvin) SUMMARY A deadlockedstateoccurs whentwo or more processes are waiting indefinitelyfor anevent that canbe causedonlybyone of the waiting processes. There are three principal methods for dealing withdeadlocks:  Use some protocol to prevent or avoiddeadlocks, ensuringthat the systemwill never enter a deadlockedstate.  Allowthe system to enter a deadlockedstate, detect it, andthenrecover.  Ignore the problem altogether andpretendthat deadlocks never occur inthe system. The thirdsolution is the one usedbymost operating systems, including Linux andWindows. A deadlock canoccur onlyif four necessaryconditions holdsimultaneouslyinthe system:mutual exclusion, holdandwait, no p reemption, andcircular wait. To prevent deadlocks, we canensure that at least one of the necessaryconditions never holds. A method for avoiding deadlocks, rather thanpreventing them, requires that the operating system have a priori informationabout how eachprocess will utilize system resources. The banker’s algorithm, for example, requires a priori informationabout the maximum number of eachresource class that each process mayrequest. Using this information, we candefine a deadlock avoidance algorithm. If a system does not employa protocol to ensure that deadlocks will never occur, then a detection-and-recoveryscheme maybe employed. A deadlock detection algorithm must be invokedto determine whether a deadlock has occurred. If a deadlock is detected, the systemmust recover either by terminatingsome ofthe deadlockedprocesses or bypreemptingresources from some of the deadlockedprocesses. Where preemption is used to dealwith deadlocks, three issues must be addressed:selectinga victim, rollback, and starvation . In a systemthat selects victims for rollback primarilyonthe basisof cost factors, starvationmayoccur, andthe selectedprocess cannever complete its designated task. Researchers have arguedthat none of the basic approachesalone is appropriate for the entire spectrum ofresource-allocationproblems inoperating systems. The basic approaches can be combined, however, allowing us to select an optimal approach for eachclass of resources in a system. AssortedContent  XXX To be cleared  I Q’s Later  XXX Glossary ReadLater Further Reading  S  Grey Areas  XXX