SlideShare a Scribd company logo
1 of 9
1
Deadlocks (Galvin Notes 9th Ed.)
Chapter 7: Deadlocks
 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)
Content
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 deadlock-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 distributed among a number of competing processes. The resources may be
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 any instance of the
type shouldsatisfythe request. For example, two printers maybe definedto be inthe same resource class if no one cares wh ich printer
prints which output.
 Chapter 5 discussedvarious synchronizationtools, suchas mutex locks andsemaphores. These toolsare alsoconsidered system 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 so forth. For that reason, each lock is typically
assigned its own resource class, and definition is not a problem.
 A process must request a resource before using it andmust release the resource after using it. Under the normal mode of operation, a
process may utilize a resource in only the following sequence: 1) Request 2) Use 3) Release
 The request andrelease of resources maybe system calls, as explained in 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 each use
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 added to
a queue of processes waiting for this resource.
 A set of processes is in a deadlockedstate wheneveryprocess in the set is waiting for anevent that canbe causedonlyby another process in
the set. A set of processes is ina deadlocked state when everyprocessinthe set is waitingfor anevent that canbe caused only by another
process inthe set. The resourcesmaybe either physical resources (for example, printers, tape drives, memory space, and CPU cycles) or
2
Deadlocks (Galvin Notes 9th Ed.)
logical resources (for example, semaphores, mutex locks, andfiles). However, other types of events mayresult in deadlocks (for example, the
IPC facilities discussed in Chapter 3).
 To illustrate a deadlocked state, consider a system withthree CD RW drives. Suppose each of three process es holds one of these 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 deadlock occurs.
 Developers of multithreaded applications must remainaware ofthe possibilityof deadlocks. The locking tools presented in Ch apter 5 are
designedto avoidrace conditions. However, inusing these tools, developers must pay careful attention to how locks are acquired and
released. Otherwise, deadlock can occur, as illustrated in the dining-philosophers problem in Section 5.7.3.
DEADLOCK CHARACTERIZATION
In a deadlock, processes never finish executing, and system resources are tiedup, preventingother jobs fromstarting. Before we discuss th e various
methods for dealing with the deadlock problem, 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:
o Mutual exclusion – At least one resource must be heldin a non-sharable mode; that is, only one process at a time can use the
resource. If another process requests that resource, the requesting process must be delayeduntil the resource has been released.
o Hold and wait – A process must be holding at least one resource andwaiting to acquire additional resources that are currentlybeing
held by other processes.
o No pre-emption – Resources cannot be preempted;that is, a resource canbe released onlyvoluntarily by the process holding it,
after that process has completed its 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 by P2, ..., Pn−1 is waiting for a resource held by Pn, and Pn is waiting for a resource held by P0.
 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 in Section 7.4, however, that it is useful to consider each condition
separately.
Resource-Allocation Graph

3
Deadlocks (Galvin Notes 9th Ed.)

 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
deadlockedstate. This observation is important when we dealwith the deadlock
problem.
METHODS FOR HANDLING DEADLOCKS
We can deal with the deadlock problem in one of three ways:
 We can use a protocol to prevent or avoid deadlocks, ensuring that the system will never enter a deadlocked state.
 We can allow the system to enter a deadlocked state, detect it, and recover.
 We can ignore the problem altogether and pretend that deadlocks never occur in the system (and restart manually).
The third solution is the one used by most operating systems, in cluding Linux and Windows.
Next, we elaborate brieflyon eachof the three methods for handling deadlocks. Then, inSections 7.4 through 7.7, we present detailed algorithms.
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 can be made.
Deadlock avoidance requires that the operatingsystem be givenadditional information in advance concerning which resources a 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 system must consider the resources curre ntly available, the
resources currently allocated to each process, and the future requests and rel eases of each process.
If a systemdoesnot employeither a deadlock-preventionor a deadlockavoidance algorithm, thena deadlocksituationmayarise. In this environment,
the systemcanprovide analgorithmthat examines the state of the system to determine whether a deadlock hasoccurred and an algorithm to recover
from the deadlock (if a deadlock has indeed occurred). We discuss these issues in Section 7.6 and Section 7.7.
4
Deadlocks (Galvin Notes 9th Ed.)
DEADLOCK PREVENTION
For a deadlock to occur, each ofthe four necessary conditions must hold. Byensuring that at least one of these conditions cannot hold, we can
prevent the occurrence of a deadlock.
 Mutual Exclusion: In general, we cannot prevent deadlocks by denying the 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 each process to request and be alloca ted all its
resources before it begins execution. We canimplement this provision byrequiring that system calls requesting resources for a process
precede all other system calls.
An alternative protocol allows a process to request resources onlywhenit hasnone. A process mayrequest some resources and use them.
Before it can request any additional resources, it must release all the resources that it is currently allocated.
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, thenthe process must initially
request the DVD drive, diskfile, andprinter. It will holdthe printer for its entire execution, even thoughit needs the printer only at the end.
The second method allows the processto request initiallyonlythe DVDdrive anddisk file. It copiesfrom the DVD drive to the disk and then
releases both the DVDdrive andthe diskfile. The process must then request the disk file and the printer. After copying the disk file to the
printer, it releases these two resources and terminates.
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 preemptionof resources that have alreadybeenallocated. To
ensure that this condition does not hold, we can use the following protocol. If a process is holding so me resources and requests another
resource that cannot be immediatelyallocatedto it (that is, the processmust wait), thenallresources the process is curre ntly holding are
preempted. In otherwords, these resources are implicitlyreleased. The preempted resources are addedto the list of resources for which the
process is waiting. The process willbe restartedonlywhen it canregain its old resources, as well as the new ones that it is requesting.
Alternatively, if a process requests some resources, we first checkwhether theyare available. If theyare, we allocate them. If they are
not, we check whether theyare allocatedto some other process that is waiting for additional resources. If so, we preempt th e desired
resources from the waitingprocessand allocate themto the requestingprocess. If the resources are neither available nor held by a waiting
process, the requestingprocess must wait. While it is waiting, some of its resources maybe preempted, but onlyif another p rocess requests
them. A process canbe restartedonlywhen it is allocated the newresourcesit is requesting andrecovers anyresources that were preempted
while it was waiting.
This protocol is oftenapplied to resources whose state can be easilysavedand restored later, suchas CPU registers and memory space. It
cannot generally be applied to such resources as mutex locks and semaphores.
 Circular Wait: The fourth and final conditionfor deadlocks is the circular-wait condition. One way to ensure that this
conditionnever holds is to imposea total ordering of all resource types and to require that each process requests
resources inanincreasing order of enumeration. To illustrate, we let R = {R1, R2, ..., Rm} be the set of resource types.
We assignto each resource 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
function F:R→N, where N is the set of natural numbers. For example, if the set of re source
types R includes tape drives, diskdrives, andprinters, thenthe functionF might be defined as
follows:
We can now consider the following protocol to prevent deadlocks: Each process can
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 and printer 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 by contradiction---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
was F(first mutex) = 1 and F(secondmutex) = 5 then thread twocouldnot request the locks out
of order. Keepin mindthat developing an ordering, or hierarchy, does not in itself prevent
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 usually needed before the printer, it would be reasonable to define F(tape drive)<F(printer).
Althoughensuring that resources are acquiredinthe proper order is the responsibilityof applicationdevelopers, certain so ftware can be
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
5
Deadlocks (Galvin Notes 9th Ed.)
use the program shown inFigure 7.4 as anexample. Assume that thread one is the first to acquire the locks anddoes so in th e order (1) first
_mutex, (2) second_mutex. Witness records the relationshipthat first mutex must be acquired before second mutex. If thread two later
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 acquired dynamically (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 tilization and reduced
system throughput.
An alternative methodfor avoidingdeadlocks is to require additional information about how resources are to be requested. Fo r 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 currently available, the resources curre ntly allocated to each
process, and the future requests and releases of 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 dynamically examines the resource -
allocationstate to ensure that a circular-wait conditioncannever exist. The resource allocation state is definedbythe number ofavailable andallocated
resources and the maximum demands of the processes. In the following sections, we explore two dead lock-avoidance algorithms.
Safe State
6
Deadlocks (Galvin Notes 9th Ed.)
Banker’s Algorithm
7
Deadlocks (Galvin Notes 9th Ed.)
DEADLOCK DETECTION
If a systemdoesnot employeither a deadlock-preventionor a deadlockavoidance algorithm, thena deadlocksituationmayoccur. Inthis environment,
the system may provide:
 An algorithm that examines the state of the system to determine whether a deadlock has occurred
 An algorithm to recover from the deadlock
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 necessaryinformationandexecuting the detection algorithm but also the potential losses
inherent in recovering from 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 byremoving 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-allocation graph and the corresponding wait-for graph.
As before, a deadlock exists in the system if andonlyif the wait-for graphcontains a cycle. To detect deadlocks, the system needs 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 in the 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 simply investigateseverypossible allocationsequence for
the processes that remainto be completed. Compare this algorithm withthe banker’s algorithm of Section7.5.3.
8
Deadlocks (Galvin Notes 9th Ed.)
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 p rocesseswill be idle until
the deadlock can be broken. In addition, the number of processes involved in the deadlock cycle may gro w.
Deadlocks occur onlywhensome processmakes a request that cannot be grantedimmediately. Thisrequest maybe the final requ est that completes
a chain ofwaiting processes. In the extreme, then, we can invoke the deadlock detectionalgorithm everytime a request for allocation cannot be granted
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, caused the deadlock.) If there are many different
resource types, one request maycreate manycycles inthe resource graph, eachcycle completedbythe most recent request and “caused” by the one
identifiable process.
Of course, invokingthe deadlock-detection algorithm for everyresource request will incur considerable overhead in computation time. A less
expensive alternative is simplyto invoke the algorithm at definedintervals—for example, once per hour or whenever CPU utilization drops below 40
percent. (A deadlock eventuallycripples systemthroughput and causes CPU utilizationto drop.) If the detection algorithm is invokedat arbitrary points
in time, the resource graphmaycontainmanycycles. Inthiscase, we generallycannot tell which of the many deadlocked processes “caused” the
deadlock.
RECOVERY FROM DEADLOCK
When a detectionalgorithmdetermines that a deadlock exists, severalalternatives are available. One possibility is to inform the operator that a
deadlock hasoccurred and to let the operator deal withthe deadlock manually. Another possibility is to let the system recover from the deadlock
automatically. There are two options for breaking a deadlock. One is simplyto abort one or more processes to break the circular wait. The other is to
preempt some resources from one or more of the deadlocked processes.
Process Termination
To eliminate deadlocks byaborting a process, we use one of two methods. In both methods, the system reclaims all resources allocated to the
terminated processes.
 Abort all deadlocked processes. This methodclearlywill break the deadlockcycle, but at great expense. The deadlocked proce sses may have
computedfor a long time, andthe results ofthese partial computations must be discarded andprobably will have to b e recomputed later.
 Abort one process at a time until the deadlock cycle is eliminated. This methodincurs 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 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. If the partial
terminationmethodis used, then we must determine which deadlockedprocess (or processes) shouldbe terminated. This determi nation is a policy
decision, similar to CPU-schedulingdecisions. The questionis basicallyaneconomic one; we should abort those processes whose termination will incur
the minimum cost. Unfortunately, the term minimum cost is not a precise one. Many factors may affect which process is chosen, including:
1. What the priority of the process is
2. How long the process has computed and how much longer the process will compute before completing its designated task
3. How many and what types of resources the process has used(for example, whether the resources are simple to preempt)
4. How many more resources the process needs in order to complete
5. How many processes will need to be terminated 6. 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 preemption is required to deal with deadlocks, then three issues need to 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 hold ing and the
amount of time the process has thus far consumed.
 Rollback. If we preempt a resource from a process, what should be done with that process? Clearly, it cannot continue with its normal
execution;it is missing some neededresource. We must roll backthe process to some safe state and restart it from that state. Since, in
general, it is difficult to determine what a safe state is, the simplest solutionis a total rollback:abort the process and thenrestart it. Althoughit
is more effective to roll back the process onlyas far as necessary to break the deadlock, this method requires the system to keep more
information about the state of all running 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 selectionis 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 process can be
pickedas a victim only a (small) finite number of times. The most common solution is to include the number of rollbacks in t he cost factor.
9
Deadlocks (Galvin Notes 9th Ed.)
SUMMARY
A deadlockedstate occurs whentwo or more processes are waiting indefinitelyfor anevent that canbe causedonlybyone of th e 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.
To be cleared
Q’s Later
ReadLater
Further Reading
Grey Areas

More Related Content

What's hot

What's hot (20)

Dead Lock In Operating Systems
Dead Lock In Operating SystemsDead Lock In Operating Systems
Dead Lock In Operating Systems
 
OS - Deadlock
OS - DeadlockOS - Deadlock
OS - Deadlock
 
Deadlock
DeadlockDeadlock
Deadlock
 
Mca ii os u-3 dead lock & io systems
Mca  ii  os u-3 dead lock & io systemsMca  ii  os u-3 dead lock & io systems
Mca ii os u-3 dead lock & io systems
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Deadlock
DeadlockDeadlock
Deadlock
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
 
Dead lock
Dead lockDead lock
Dead lock
 
Deadlocks
 Deadlocks Deadlocks
Deadlocks
 
Methods for handling deadlocks
Methods for handling deadlocksMethods for handling deadlocks
Methods for handling deadlocks
 
10. deadlock
10. deadlock10. deadlock
10. deadlock
 
Deadlock Presentation
Deadlock PresentationDeadlock Presentation
Deadlock Presentation
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
 
deadlock
deadlockdeadlock
deadlock
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
 
Deadlock in Operating System
Deadlock in Operating SystemDeadlock in Operating System
Deadlock in Operating System
 
Operating system - Deadlock
Operating system - DeadlockOperating system - Deadlock
Operating system - Deadlock
 
Ch 4 deadlock
Ch 4 deadlockCh 4 deadlock
Ch 4 deadlock
 
Gp1242 007 oer ppt
Gp1242 007 oer pptGp1242 007 oer ppt
Gp1242 007 oer ppt
 

Viewers also liked

Ninth class biology mcqs ( classification of living organisms)
Ninth class biology mcqs ( classification of living organisms)Ninth class biology mcqs ( classification of living organisms)
Ninth class biology mcqs ( classification of living organisms)Dr. Sajid Ali Talpur
 
Biology Notes for Class 9th (by: Seetal Daas)
Biology Notes for Class 9th (by: Seetal Daas)Biology Notes for Class 9th (by: Seetal Daas)
Biology Notes for Class 9th (by: Seetal Daas)Seetal Daas
 
(1st) first year HSSC I part 1 English Notes( short question answers and boo...
(1st) first year HSSC I  part 1 English Notes( short question answers and boo...(1st) first year HSSC I  part 1 English Notes( short question answers and boo...
(1st) first year HSSC I part 1 English Notes( short question answers and boo...Bt Yb
 
Ninth class biology mcqs (the cell)
Ninth class biology mcqs (the cell)Ninth class biology mcqs (the cell)
Ninth class biology mcqs (the cell)Dr. Sajid Ali Talpur
 
Biology MCQs (Multiple Choice Questions)
Biology MCQs (Multiple Choice Questions)Biology MCQs (Multiple Choice Questions)
Biology MCQs (Multiple Choice Questions)Biology Exams 4 U
 
Mcq 1060 questions
Mcq 1060 questionsMcq 1060 questions
Mcq 1060 questionsadrioz
 

Viewers also liked (10)

Ninth class biology mcqs ( classification of living organisms)
Ninth class biology mcqs ( classification of living organisms)Ninth class biology mcqs ( classification of living organisms)
Ninth class biology mcqs ( classification of living organisms)
 
Biology Notes for Class 9th (by: Seetal Daas)
Biology Notes for Class 9th (by: Seetal Daas)Biology Notes for Class 9th (by: Seetal Daas)
Biology Notes for Class 9th (by: Seetal Daas)
 
Book notes- Book-I & Book-III
Book notes- Book-I & Book-IIIBook notes- Book-I & Book-III
Book notes- Book-I & Book-III
 
(1st) first year HSSC I part 1 English Notes( short question answers and boo...
(1st) first year HSSC I  part 1 English Notes( short question answers and boo...(1st) first year HSSC I  part 1 English Notes( short question answers and boo...
(1st) first year HSSC I part 1 English Notes( short question answers and boo...
 
Biology 9th
Biology 9thBiology 9th
Biology 9th
 
Ninth class biology mcqs (the cell)
Ninth class biology mcqs (the cell)Ninth class biology mcqs (the cell)
Ninth class biology mcqs (the cell)
 
Biology MCQs (Multiple Choice Questions)
Biology MCQs (Multiple Choice Questions)Biology MCQs (Multiple Choice Questions)
Biology MCQs (Multiple Choice Questions)
 
Chemistry Fsc Part 1 All chapter MCQs
Chemistry Fsc Part 1 All chapter MCQs Chemistry Fsc Part 1 All chapter MCQs
Chemistry Fsc Part 1 All chapter MCQs
 
1st Year English Book Notes (HSSC-I)
1st Year English Book Notes (HSSC-I)1st Year English Book Notes (HSSC-I)
1st Year English Book Notes (HSSC-I)
 
Mcq 1060 questions
Mcq 1060 questionsMcq 1060 questions
Mcq 1060 questions
 

Similar to Deadlocks final (20)

Deadlocksprefinal 161014115456
Deadlocksprefinal 161014115456Deadlocksprefinal 161014115456
Deadlocksprefinal 161014115456
 
Module3
Module3Module3
Module3
 
Os module 2 d
Os module 2 dOs module 2 d
Os module 2 d
 
Deadlock and memory management -- Operating System
Deadlock and memory management -- Operating SystemDeadlock and memory management -- Operating System
Deadlock and memory management -- Operating System
 
OS 7.pptx
OS 7.pptxOS 7.pptx
OS 7.pptx
 
Deadlock
DeadlockDeadlock
Deadlock
 
operating system
operating systemoperating system
operating system
 
operating system
operating systemoperating system
operating system
 
Sucet os module_3_notes
Sucet os module_3_notesSucet os module_3_notes
Sucet os module_3_notes
 
Distributed deadlock
Distributed deadlockDistributed deadlock
Distributed deadlock
 
Os case study word
Os case study wordOs case study word
Os case study word
 
osvishal-160830131208 (1).pdf
osvishal-160830131208 (1).pdfosvishal-160830131208 (1).pdf
osvishal-160830131208 (1).pdf
 
Deadlock
DeadlockDeadlock
Deadlock
 
Deadlock
DeadlockDeadlock
Deadlock
 
Deadlock
DeadlockDeadlock
Deadlock
 
Deadlock in Distributed Systems
Deadlock in Distributed SystemsDeadlock in Distributed Systems
Deadlock in Distributed Systems
 
Chapter 03
Chapter 03Chapter 03
Chapter 03
 
Operating System Deadlock Galvin
Operating System  Deadlock GalvinOperating System  Deadlock Galvin
Operating System Deadlock Galvin
 
osvzjsjjdndnnssnnsnsndndndnndeadlock.pptx
osvzjsjjdndnnssnnsnsndndndnndeadlock.pptxosvzjsjjdndnnssnnsnsndndndnndeadlock.pptx
osvzjsjjdndnnssnnsnsndndndnndeadlock.pptx
 
Operating system Deadlock
Operating system DeadlockOperating system Deadlock
Operating system Deadlock
 

More from marangburu42

Hennchthree 161102111515
Hennchthree 161102111515Hennchthree 161102111515
Hennchthree 161102111515marangburu42
 
Sequential circuits
Sequential circuitsSequential circuits
Sequential circuitsmarangburu42
 
Combinational circuits
Combinational circuitsCombinational circuits
Combinational circuitsmarangburu42
 
Hennchthree 160912095304
Hennchthree 160912095304Hennchthree 160912095304
Hennchthree 160912095304marangburu42
 
Sequential circuits
Sequential circuitsSequential circuits
Sequential circuitsmarangburu42
 
Combinational circuits
Combinational circuitsCombinational circuits
Combinational circuitsmarangburu42
 
Karnaugh mapping allaboutcircuits
Karnaugh mapping allaboutcircuitsKarnaugh mapping allaboutcircuits
Karnaugh mapping allaboutcircuitsmarangburu42
 
Aac boolean formulae
Aac   boolean formulaeAac   boolean formulae
Aac boolean formulaemarangburu42
 
Virtualmemoryfinal 161019175858
Virtualmemoryfinal 161019175858Virtualmemoryfinal 161019175858
Virtualmemoryfinal 161019175858marangburu42
 
File system interfacefinal
File system interfacefinalFile system interfacefinal
File system interfacefinalmarangburu42
 
File systemimplementationfinal
File systemimplementationfinalFile systemimplementationfinal
File systemimplementationfinalmarangburu42
 
Mass storage structurefinal
Mass storage structurefinalMass storage structurefinal
Mass storage structurefinalmarangburu42
 
All aboutcircuits karnaugh maps
All aboutcircuits karnaugh mapsAll aboutcircuits karnaugh maps
All aboutcircuits karnaugh mapsmarangburu42
 
Virtual memoryfinal
Virtual memoryfinalVirtual memoryfinal
Virtual memoryfinalmarangburu42
 
Mainmemoryfinal 161019122029
Mainmemoryfinal 161019122029Mainmemoryfinal 161019122029
Mainmemoryfinal 161019122029marangburu42
 

More from marangburu42 (20)

Hol
HolHol
Hol
 
Write miss
Write missWrite miss
Write miss
 
Hennchthree 161102111515
Hennchthree 161102111515Hennchthree 161102111515
Hennchthree 161102111515
 
Hennchthree
HennchthreeHennchthree
Hennchthree
 
Hennchthree
HennchthreeHennchthree
Hennchthree
 
Sequential circuits
Sequential circuitsSequential circuits
Sequential circuits
 
Combinational circuits
Combinational circuitsCombinational circuits
Combinational circuits
 
Hennchthree 160912095304
Hennchthree 160912095304Hennchthree 160912095304
Hennchthree 160912095304
 
Sequential circuits
Sequential circuitsSequential circuits
Sequential circuits
 
Combinational circuits
Combinational circuitsCombinational circuits
Combinational circuits
 
Karnaugh mapping allaboutcircuits
Karnaugh mapping allaboutcircuitsKarnaugh mapping allaboutcircuits
Karnaugh mapping allaboutcircuits
 
Aac boolean formulae
Aac   boolean formulaeAac   boolean formulae
Aac boolean formulae
 
Virtualmemoryfinal 161019175858
Virtualmemoryfinal 161019175858Virtualmemoryfinal 161019175858
Virtualmemoryfinal 161019175858
 
Io systems final
Io systems finalIo systems final
Io systems final
 
File system interfacefinal
File system interfacefinalFile system interfacefinal
File system interfacefinal
 
File systemimplementationfinal
File systemimplementationfinalFile systemimplementationfinal
File systemimplementationfinal
 
Mass storage structurefinal
Mass storage structurefinalMass storage structurefinal
Mass storage structurefinal
 
All aboutcircuits karnaugh maps
All aboutcircuits karnaugh mapsAll aboutcircuits karnaugh maps
All aboutcircuits karnaugh maps
 
Virtual memoryfinal
Virtual memoryfinalVirtual memoryfinal
Virtual memoryfinal
 
Mainmemoryfinal 161019122029
Mainmemoryfinal 161019122029Mainmemoryfinal 161019122029
Mainmemoryfinal 161019122029
 

Recently uploaded

(NEHA) Call Girls Ahmedabad Booking Open 8617697112 Ahmedabad Escorts
(NEHA) Call Girls Ahmedabad Booking Open 8617697112 Ahmedabad Escorts(NEHA) Call Girls Ahmedabad Booking Open 8617697112 Ahmedabad Escorts
(NEHA) Call Girls Ahmedabad Booking Open 8617697112 Ahmedabad EscortsCall girls in Ahmedabad High profile
 
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...akbard9823
 
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur DubaiBur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubaidajasot375
 
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad EscortsIslamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escortswdefrd
 
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...wdefrd
 
Call Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceCall Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceAyesha Khan
 
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | DelhiMalviyaNagarCallGirl
 
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call GirlsJagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girlsashishs7044
 
MinSheng Gaofeng Estate commercial storyboard
MinSheng Gaofeng Estate commercial storyboardMinSheng Gaofeng Estate commercial storyboard
MinSheng Gaofeng Estate commercial storyboardjessica288382
 
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | DelhiFULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
FULL ENJOY - 9953040155 Call Girls in Shahdara | DelhiFULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
FULL ENJOY - 9953040155 Call Girls in Shahdara | DelhiMalviyaNagarCallGirl
 
San Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMSan Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMroute66connected
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...akbard9823
 
Turn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel JohnsonTurn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel Johnsonthephillipta
 
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...dajasot375
 
Akola Call Girls #9907093804 Contact Number Escorts Service Akola
Akola Call Girls #9907093804 Contact Number Escorts Service AkolaAkola Call Girls #9907093804 Contact Number Escorts Service Akola
Akola Call Girls #9907093804 Contact Number Escorts Service Akolasrsj9000
 
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKRAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKedwardsara83
 
Karachi Escorts | +923070433345 | Escort Service in Karachi
Karachi Escorts | +923070433345 | Escort Service in KarachiKarachi Escorts | +923070433345 | Escort Service in Karachi
Karachi Escorts | +923070433345 | Escort Service in KarachiAyesha Khan
 
Olivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxOlivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxLauraFagan6
 
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiFULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiMalviyaNagarCallGirl
 

Recently uploaded (20)

(NEHA) Call Girls Ahmedabad Booking Open 8617697112 Ahmedabad Escorts
(NEHA) Call Girls Ahmedabad Booking Open 8617697112 Ahmedabad Escorts(NEHA) Call Girls Ahmedabad Booking Open 8617697112 Ahmedabad Escorts
(NEHA) Call Girls Ahmedabad Booking Open 8617697112 Ahmedabad Escorts
 
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
 
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur DubaiBur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
 
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad EscortsIslamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
Islamabad Call Girls # 03091665556 # Call Girls in Islamabad | Islamabad Escorts
 
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
 
Call Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl ServiceCall Girls in Islamabad | 03274100048 | Call Girl Service
Call Girls in Islamabad | 03274100048 | Call Girl Service
 
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
 
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call GirlsJagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
Jagat Puri Call Girls : ☎ 8527673949, Low rate Call Girls
 
MinSheng Gaofeng Estate commercial storyboard
MinSheng Gaofeng Estate commercial storyboardMinSheng Gaofeng Estate commercial storyboard
MinSheng Gaofeng Estate commercial storyboard
 
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | DelhiFULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
FULL ENJOY - 9953040155 Call Girls in Dwarka Mor | Delhi
 
FULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
FULL ENJOY - 9953040155 Call Girls in Shahdara | DelhiFULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
FULL ENJOY - 9953040155 Call Girls in Shahdara | Delhi
 
San Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NMSan Jon Motel, Motel/Residence, San Jon NM
San Jon Motel, Motel/Residence, San Jon NM
 
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...Patrakarpuram ) Cheap Call Girls In Lucknow  (Adult Only) 🧈 8923113531 𓀓 Esco...
Patrakarpuram ) Cheap Call Girls In Lucknow (Adult Only) 🧈 8923113531 𓀓 Esco...
 
Turn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel JohnsonTurn Lock Take Key Storyboard Daniel Johnson
Turn Lock Take Key Storyboard Daniel Johnson
 
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
Call Girl in Bur Dubai O5286O4116 Indian Call Girls in Bur Dubai By VIP Bur D...
 
Akola Call Girls #9907093804 Contact Number Escorts Service Akola
Akola Call Girls #9907093804 Contact Number Escorts Service AkolaAkola Call Girls #9907093804 Contact Number Escorts Service Akola
Akola Call Girls #9907093804 Contact Number Escorts Service Akola
 
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKRAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
 
Karachi Escorts | +923070433345 | Escort Service in Karachi
Karachi Escorts | +923070433345 | Escort Service in KarachiKarachi Escorts | +923070433345 | Escort Service in Karachi
Karachi Escorts | +923070433345 | Escort Service in Karachi
 
Olivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptxOlivia Cox. intertextual references.pptx
Olivia Cox. intertextual references.pptx
 
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiFULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
 

Deadlocks final

  • 1. 1 Deadlocks (Galvin Notes 9th Ed.) Chapter 7: Deadlocks  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) Content 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 deadlock-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 distributed among a number of competing processes. The resources may be 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 any instance of the type shouldsatisfythe request. For example, two printers maybe definedto be inthe same resource class if no one cares wh ich printer prints which output.  Chapter 5 discussedvarious synchronizationtools, suchas mutex locks andsemaphores. These toolsare alsoconsidered system 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 so forth. For that reason, each lock is typically assigned its own resource class, and definition is not a problem.  A process must request a resource before using it andmust release the resource after using it. Under the normal mode of operation, a process may utilize a resource in only the following sequence: 1) Request 2) Use 3) Release  The request andrelease of resources maybe system calls, as explained in 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 each use 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 added to a queue of processes waiting for this resource.  A set of processes is in a deadlockedstate wheneveryprocess in the set is waiting for anevent that canbe causedonlyby another process in the set. A set of processes is ina deadlocked state when everyprocessinthe set is waitingfor anevent that canbe caused only by another process inthe set. The resourcesmaybe either physical resources (for example, printers, tape drives, memory space, and CPU cycles) or
  • 2. 2 Deadlocks (Galvin Notes 9th Ed.) logical resources (for example, semaphores, mutex locks, andfiles). However, other types of events mayresult in deadlocks (for example, the IPC facilities discussed in Chapter 3).  To illustrate a deadlocked state, consider a system withthree CD RW drives. Suppose each of three process es holds one of these 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 deadlock occurs.  Developers of multithreaded applications must remainaware ofthe possibilityof deadlocks. The locking tools presented in Ch apter 5 are designedto avoidrace conditions. However, inusing these tools, developers must pay careful attention to how locks are acquired and released. Otherwise, deadlock can occur, as illustrated in the dining-philosophers problem in Section 5.7.3. DEADLOCK CHARACTERIZATION In a deadlock, processes never finish executing, and system resources are tiedup, preventingother jobs fromstarting. Before we discuss th e various methods for dealing with the deadlock problem, 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: o Mutual exclusion – At least one resource must be heldin a non-sharable mode; that is, only one process at a time can use the resource. If another process requests that resource, the requesting process must be delayeduntil the resource has been released. o Hold and wait – A process must be holding at least one resource andwaiting to acquire additional resources that are currentlybeing held by other processes. o No pre-emption – Resources cannot be preempted;that is, a resource canbe released onlyvoluntarily by the process holding it, after that process has completed its 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 by P2, ..., Pn−1 is waiting for a resource held by Pn, and Pn is waiting for a resource held by P0.  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 in Section 7.4, however, that it is useful to consider each condition separately. Resource-Allocation Graph 
  • 3. 3 Deadlocks (Galvin Notes 9th Ed.)   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 deadlockedstate. This observation is important when we dealwith the deadlock problem. METHODS FOR HANDLING DEADLOCKS We can deal with the deadlock problem in one of three ways:  We can use a protocol to prevent or avoid deadlocks, ensuring that the system will never enter a deadlocked state.  We can allow the system to enter a deadlocked state, detect it, and recover.  We can ignore the problem altogether and pretend that deadlocks never occur in the system (and restart manually). The third solution is the one used by most operating systems, in cluding Linux and Windows. Next, we elaborate brieflyon eachof the three methods for handling deadlocks. Then, inSections 7.4 through 7.7, we present detailed algorithms. 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 can be made. Deadlock avoidance requires that the operatingsystem be givenadditional information in advance concerning which resources a 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 system must consider the resources curre ntly available, the resources currently allocated to each process, and the future requests and rel eases of each process. If a systemdoesnot employeither a deadlock-preventionor a deadlockavoidance algorithm, thena deadlocksituationmayarise. In this environment, the systemcanprovide analgorithmthat examines the state of the system to determine whether a deadlock hasoccurred and an algorithm to recover from the deadlock (if a deadlock has indeed occurred). We discuss these issues in Section 7.6 and Section 7.7.
  • 4. 4 Deadlocks (Galvin Notes 9th Ed.) DEADLOCK PREVENTION For a deadlock to occur, each ofthe four necessary conditions must hold. Byensuring that at least one of these conditions cannot hold, we can prevent the occurrence of a deadlock.  Mutual Exclusion: In general, we cannot prevent deadlocks by denying the 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 each process to request and be alloca ted all its resources before it begins execution. We canimplement this provision byrequiring that system calls requesting resources for a process precede all other system calls. An alternative protocol allows a process to request resources onlywhenit hasnone. A process mayrequest some resources and use them. Before it can request any additional resources, it must release all the resources that it is currently allocated. 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, thenthe process must initially request the DVD drive, diskfile, andprinter. It will holdthe printer for its entire execution, even thoughit needs the printer only at the end. The second method allows the processto request initiallyonlythe DVDdrive anddisk file. It copiesfrom the DVD drive to the disk and then releases both the DVDdrive andthe diskfile. The process must then request the disk file and the printer. After copying the disk file to the printer, it releases these two resources and terminates. 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 preemptionof resources that have alreadybeenallocated. To ensure that this condition does not hold, we can use the following protocol. If a process is holding so me resources and requests another resource that cannot be immediatelyallocatedto it (that is, the processmust wait), thenallresources the process is curre ntly holding are preempted. In otherwords, these resources are implicitlyreleased. The preempted resources are addedto the list of resources for which the process is waiting. The process willbe restartedonlywhen it canregain its old resources, as well as the new ones that it is requesting. Alternatively, if a process requests some resources, we first checkwhether theyare available. If theyare, we allocate them. If they are not, we check whether theyare allocatedto some other process that is waiting for additional resources. If so, we preempt th e desired resources from the waitingprocessand allocate themto the requestingprocess. If the resources are neither available nor held by a waiting process, the requestingprocess must wait. While it is waiting, some of its resources maybe preempted, but onlyif another p rocess requests them. A process canbe restartedonlywhen it is allocated the newresourcesit is requesting andrecovers anyresources that were preempted while it was waiting. This protocol is oftenapplied to resources whose state can be easilysavedand restored later, suchas CPU registers and memory space. It cannot generally be applied to such resources as mutex locks and semaphores.  Circular Wait: The fourth and final conditionfor deadlocks is the circular-wait condition. One way to ensure that this conditionnever holds is to imposea total ordering of all resource types and to require that each process requests resources inanincreasing order of enumeration. To illustrate, we let R = {R1, R2, ..., Rm} be the set of resource types. We assignto each resource 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 function F:R→N, where N is the set of natural numbers. For example, if the set of re source types R includes tape drives, diskdrives, andprinters, thenthe functionF might be defined as follows: We can now consider the following protocol to prevent deadlocks: Each process can 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 and printer 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 by contradiction---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 was F(first mutex) = 1 and F(secondmutex) = 5 then thread twocouldnot request the locks out of order. Keepin mindthat developing an ordering, or hierarchy, does not in itself prevent 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 usually needed before the printer, it would be reasonable to define F(tape drive)<F(printer). Althoughensuring that resources are acquiredinthe proper order is the responsibilityof applicationdevelopers, certain so ftware can be 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
  • 5. 5 Deadlocks (Galvin Notes 9th Ed.) use the program shown inFigure 7.4 as anexample. Assume that thread one is the first to acquire the locks anddoes so in th e order (1) first _mutex, (2) second_mutex. Witness records the relationshipthat first mutex must be acquired before second mutex. If thread two later 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 acquired dynamically (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 tilization and reduced system throughput. An alternative methodfor avoidingdeadlocks is to require additional information about how resources are to be requested. Fo r 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 currently available, the resources curre ntly allocated to each process, and the future requests and releases of 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 dynamically examines the resource - allocationstate to ensure that a circular-wait conditioncannever exist. The resource allocation state is definedbythe number ofavailable andallocated resources and the maximum demands of the processes. In the following sections, we explore two dead lock-avoidance algorithms. Safe State
  • 6. 6 Deadlocks (Galvin Notes 9th Ed.) Banker’s Algorithm
  • 7. 7 Deadlocks (Galvin Notes 9th Ed.) DEADLOCK DETECTION If a systemdoesnot employeither a deadlock-preventionor a deadlockavoidance algorithm, thena deadlocksituationmayoccur. Inthis environment, the system may provide:  An algorithm that examines the state of the system to determine whether a deadlock has occurred  An algorithm to recover from the deadlock 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 necessaryinformationandexecuting the detection algorithm but also the potential losses inherent in recovering from 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 byremoving 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-allocation graph and the corresponding wait-for graph. As before, a deadlock exists in the system if andonlyif the wait-for graphcontains a cycle. To detect deadlocks, the system needs 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 in the 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 simply investigateseverypossible allocationsequence for the processes that remainto be completed. Compare this algorithm withthe banker’s algorithm of Section7.5.3.
  • 8. 8 Deadlocks (Galvin Notes 9th Ed.) 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 p rocesseswill be idle until the deadlock can be broken. In addition, the number of processes involved in the deadlock cycle may gro w. Deadlocks occur onlywhensome processmakes a request that cannot be grantedimmediately. Thisrequest maybe the final requ est that completes a chain ofwaiting processes. In the extreme, then, we can invoke the deadlock detectionalgorithm everytime a request for allocation cannot be granted 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, caused the deadlock.) If there are many different resource types, one request maycreate manycycles inthe resource graph, eachcycle completedbythe most recent request and “caused” by the one identifiable process. Of course, invokingthe deadlock-detection algorithm for everyresource request will incur considerable overhead in computation time. A less expensive alternative is simplyto invoke the algorithm at definedintervals—for example, once per hour or whenever CPU utilization drops below 40 percent. (A deadlock eventuallycripples systemthroughput and causes CPU utilizationto drop.) If the detection algorithm is invokedat arbitrary points in time, the resource graphmaycontainmanycycles. Inthiscase, we generallycannot tell which of the many deadlocked processes “caused” the deadlock. RECOVERY FROM DEADLOCK When a detectionalgorithmdetermines that a deadlock exists, severalalternatives are available. One possibility is to inform the operator that a deadlock hasoccurred and to let the operator deal withthe deadlock manually. Another possibility is to let the system recover from the deadlock automatically. There are two options for breaking a deadlock. One is simplyto abort one or more processes to break the circular wait. The other is to preempt some resources from one or more of the deadlocked processes. Process Termination To eliminate deadlocks byaborting a process, we use one of two methods. In both methods, the system reclaims all resources allocated to the terminated processes.  Abort all deadlocked processes. This methodclearlywill break the deadlockcycle, but at great expense. The deadlocked proce sses may have computedfor a long time, andthe results ofthese partial computations must be discarded andprobably will have to b e recomputed later.  Abort one process at a time until the deadlock cycle is eliminated. This methodincurs 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 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. If the partial terminationmethodis used, then we must determine which deadlockedprocess (or processes) shouldbe terminated. This determi nation is a policy decision, similar to CPU-schedulingdecisions. The questionis basicallyaneconomic one; we should abort those processes whose termination will incur the minimum cost. Unfortunately, the term minimum cost is not a precise one. Many factors may affect which process is chosen, including: 1. What the priority of the process is 2. How long the process has computed and how much longer the process will compute before completing its designated task 3. How many and what types of resources the process has used(for example, whether the resources are simple to preempt) 4. How many more resources the process needs in order to complete 5. How many processes will need to be terminated 6. 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 preemption is required to deal with deadlocks, then three issues need to 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 hold ing and the amount of time the process has thus far consumed.  Rollback. If we preempt a resource from a process, what should be done with that process? Clearly, it cannot continue with its normal execution;it is missing some neededresource. We must roll backthe process to some safe state and restart it from that state. Since, in general, it is difficult to determine what a safe state is, the simplest solutionis a total rollback:abort the process and thenrestart it. Althoughit is more effective to roll back the process onlyas far as necessary to break the deadlock, this method requires the system to keep more information about the state of all running 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 selectionis 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 process can be pickedas a victim only a (small) finite number of times. The most common solution is to include the number of rollbacks in t he cost factor.
  • 9. 9 Deadlocks (Galvin Notes 9th Ed.) SUMMARY A deadlockedstate occurs whentwo or more processes are waiting indefinitelyfor anevent that canbe causedonlybyone of th e 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. To be cleared Q’s Later ReadLater Further Reading Grey Areas