Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
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

Recommended for you

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

This document summarizes a chapter on deadlocks from an operating systems textbook. It defines deadlock as when a set of blocked processes wait for resources held by each other. Four conditions must be met for deadlock to occur: mutual exclusion, hold and wait, no preemption, and circular wait. Methods to handle deadlocks include prevention, avoidance, detection, and recovery. Prevention ensures deadlocks cannot occur by restricting resource usage. Avoidance dynamically checks the system state remains safe to prevent deadlocks. Detection allows deadlocks but recovers the system. Recovery options are terminating processes or preempting resources.

Chapter 4
Chapter 4Chapter 4
Chapter 4

Definition,Deadlock characteristics , Deadlock Prevention , Deadlock Avoidance :banker’s algorithm, Deadlock detection and Recovery.

Deadlock
DeadlockDeadlock
Deadlock

This document discusses deadlocks in operating systems. It defines deadlock as when multiple processes are waiting for resources held by each other in a cyclic manner, resulting in none of the processes making progress. It provides examples and describes the four necessary conditions for deadlock to occur: mutual exclusion, hold and wait, no preemption, and circular wait. It also discusses methods for handling deadlocks, including prevention, avoidance, and recovery techniques like terminating processes or preempting resources.

deadlock
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.

Recommended for you

DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems

Deadlocks-An Unconditional Waiting Situation in Operating System. We must make sure of This concept well before understanding deep in to Operating System. This PPT will understands you to get how the deadlocks Occur and how can we Detect, avoid and Prevent the deadlocks in Operating Systems.

deadlocksdeadlock avoidancedeadlock prevention
Dead lock
Dead lockDead lock
Dead lock

This document defines and explains deadlocks in an operating system. A deadlock occurs when a set of processes are blocked waiting for resources held by other processes in the set, resulting in a circular wait. Four necessary conditions for deadlock are mutual exclusion, hold and wait, no preemption, and circular wait. Resource allocation graphs can be used to visualize resource allocation relations between processes and determine if a deadlock has occurred. Methods for recovering from deadlock include violating mutual exclusion, preempting resources from processes, and aborting processes. The operating system may also ignore deadlocks altogether.

Deadlocks
 Deadlocks Deadlocks
Deadlocks

The document discusses deadlocks in operating systems. It defines deadlocks and explains the four necessary conditions for a deadlock to occur: mutual exclusion, hold and wait, no preemption, and circular wait. It then describes different strategies for handling deadlocks, including prevention, avoidance, detection, and recovery.

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

Dead Lock In Operating Systems
Dead Lock In Operating SystemsDead Lock In Operating Systems
Dead Lock In Operating Systems
totallooser
 
OS - Deadlock
OS - DeadlockOS - Deadlock
OS - Deadlock
vinay arora
 
Deadlock
DeadlockDeadlock
Deadlock
Mohd Arif
 
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
Rai University
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
ushabarad142
 
Deadlock
DeadlockDeadlock
Deadlock
Sajan Sahu
 
DeadLock in Operating-Systems
DeadLock in Operating-SystemsDeadLock in Operating-Systems
DeadLock in Operating-Systems
Venkata Sreeram
 
Dead lock
Dead lockDead lock
Dead lock
M_Javed Ashraf
 
Deadlocks
 Deadlocks Deadlocks
Deadlocks
Dilshan Sudaraka
 
Methods for handling deadlocks
Methods for handling deadlocksMethods for handling deadlocks
Methods for handling deadlocks
A. S. M. Shafi
 
10. deadlock
10. deadlock10. deadlock
10. deadlock
Robbie AkaChopa
 
Deadlock Presentation
Deadlock PresentationDeadlock Presentation
Deadlock Presentation
salmancreation
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
Shipra Swati
 
deadlock
deadlockdeadlock
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
lalithambiga kamaraj
 
Deadlocks in operating system
Deadlocks in operating systemDeadlocks in operating system
Deadlocks in operating system
Sara Ali
 
Deadlock in Operating System
Deadlock in Operating SystemDeadlock in Operating System
Deadlock in Operating System
AUST
 
Operating system - Deadlock
Operating system - DeadlockOperating system - Deadlock
Operating system - Deadlock
Shashank Yenurkar
 
Ch 4 deadlock
Ch 4 deadlockCh 4 deadlock
Ch 4 deadlock
madhuributani
 
Gp1242 007 oer ppt
Gp1242 007 oer pptGp1242 007 oer ppt
Gp1242 007 oer ppt
Nivedita Kasturi
 

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
 
Book notes- Book-I & Book-III
Book notes- Book-I & Book-IIIBook 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...
Bt Yb
 
Biology 9th
Biology 9thBiology 9th
Biology 9th
Noor Rahman
 
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
 
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
http://www.daecivil.com
 
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)
MUHAMMAD AZAM, VICE PRINCIPAL IMSB G-6/4, ISLAMABAD
 
Mcq 1060 questions
Mcq 1060 questionsMcq 1060 questions
Mcq 1060 questions
adrioz
 

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

Deadlocksprefinal 161014115456
Deadlocksprefinal 161014115456Deadlocksprefinal 161014115456
Deadlocksprefinal 161014115456
marangburu42
 
Module3
Module3Module3
Module3
dilshad begum
 
Os module 2 d
Os module 2 dOs module 2 d
Os module 2 d
Gichelle Amon
 
Deadlock and memory management -- Operating System
Deadlock and memory management -- Operating SystemDeadlock and memory management -- Operating System
Deadlock and memory management -- Operating System
EktaVaswani2
 
OS 7.pptx
OS 7.pptxOS 7.pptx
OS 7.pptx
ZainabShahzad9
 
Deadlock
DeadlockDeadlock
Deadlock
Mahershi ACT
 
operating system
operating systemoperating system
operating system
renukarenuka9
 
operating system
operating systemoperating system
operating system
renukarenuka9
 
Sucet os module_3_notes
Sucet os module_3_notesSucet os module_3_notes
Sucet os module_3_notes
SRINIVASUNIVERSITYEN
 
Distributed deadlock
Distributed deadlockDistributed deadlock
Distributed deadlock
Md. Mahedi Mahfuj
 
Os case study word
Os case study wordOs case study word
Os case study word
Dhol Yash
 
osvishal-160830131208 (1).pdf
osvishal-160830131208 (1).pdfosvishal-160830131208 (1).pdf
osvishal-160830131208 (1).pdf
amadayshwan
 
Deadlock
DeadlockDeadlock
Deadlock
VISHAL DONGA
 
Deadlock
DeadlockDeadlock
Deadlock
Abhinaw Rai
 
Deadlock
DeadlockDeadlock
Deadlock in Distributed Systems
Deadlock in Distributed SystemsDeadlock in Distributed Systems
Deadlock in Distributed Systems
Pritom Saha Akash
 
Chapter 03
Chapter 03Chapter 03
Chapter 03
Google
 
Operating System Deadlock Galvin
Operating System  Deadlock GalvinOperating System  Deadlock Galvin
Operating System Deadlock Galvin
Sonali Chauhan
 
osvzjsjjdndnnssnnsnsndndndnndeadlock.pptx
osvzjsjjdndnnssnnsnsndndndnndeadlock.pptxosvzjsjjdndnnssnnsnsndndndnndeadlock.pptx
osvzjsjjdndnnssnnsnsndndndnndeadlock.pptx
Bhaskar271887
 
Operating system Deadlock
Operating system DeadlockOperating system Deadlock

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

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

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

Matka India Sattamatka Dp boss Today matka
Matka India Sattamatka Dp boss Today matkaMatka India Sattamatka Dp boss Today matka
Matka India Sattamatka Dp boss Today matka
➐➑➎➎➑⓿➊➒➌➎ SATTA MATKA DP BOSS KALYAN RESULT
 
@Call @Girls in Pune 🚒 0000000000 🚒 Tanu Sharma Best High Class Pune Available
@Call @Girls in Pune 🚒 0000000000 🚒 Tanu Sharma Best High Class Pune Available@Call @Girls in Pune 🚒 0000000000 🚒 Tanu Sharma Best High Class Pune Available
@Call @Girls in Pune 🚒 0000000000 🚒 Tanu Sharma Best High Class Pune Available
ritu36392
 
Daryaganj @ℂall @Girls ꧁❤ 9711199012 ❤꧂Fabulous sonam Mehra Top Model Safe
Daryaganj @ℂall @Girls ꧁❤ 9711199012 ❤꧂Fabulous sonam Mehra Top Model SafeDaryaganj @ℂall @Girls ꧁❤ 9711199012 ❤꧂Fabulous sonam Mehra Top Model Safe
Daryaganj @ℂall @Girls ꧁❤ 9711199012 ❤꧂Fabulous sonam Mehra Top Model Safe
anchal singh$A17
 
Satta Matka Matka king DP boss Indian Matka Matka Kalyan
Satta Matka Matka king DP boss Indian Matka Matka KalyanSatta Matka Matka king DP boss Indian Matka Matka Kalyan
Satta Matka Matka king DP boss Indian Matka Matka Kalyan
➐➑➎➎➑⓿➊➒➌➎ SATTA MATKA DP BOSS KALYAN RESULT
 
Chandigarh @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
Chandigarh @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My homeChandigarh @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
Chandigarh @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
mriyagarg453
 
Common Types of Dementia 8F who notes progressive memory loss
Common Types of Dementia 8F who notes progressive memory lossCommon Types of Dementia 8F who notes progressive memory loss
Common Types of Dementia 8F who notes progressive memory loss
bilalpakweb
 
Preventing Dementia - The Basics Millions of results on Google…
Preventing Dementia - The Basics Millions of results on Google…Preventing Dementia - The Basics Millions of results on Google…
Preventing Dementia - The Basics Millions of results on Google…
bilalpakweb
 
202254.com《长相思第二季》在线观看,最新电视剧《长相思第二季》在线播放,长相思第二季今天开播了,全网最高清电视剧免费播放
202254.com《长相思第二季》在线观看,最新电视剧《长相思第二季》在线播放,长相思第二季今天开播了,全网最高清电视剧免费播放202254.com《长相思第二季》在线观看,最新电视剧《长相思第二季》在线播放,长相思第二季今天开播了,全网最高清电视剧免费播放
202254.com《长相思第二季》在线观看,最新电视剧《长相思第二季》在线播放,长相思第二季今天开播了,全网最高清电视剧免费播放
ffg01100
 
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart Madhur Matka...
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan  Chart Madhur Matka...➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan  Chart Madhur Matka...
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart Madhur Matka...
⑨③④⑧⑧③⑥⑧⑧⑦Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
 
➒➌➍➑➑➌➏➑➑➐ Satta Matta Matka Indian Matka Satta Matka Dpboss Matka boss otg
➒➌➍➑➑➌➏➑➑➐ Satta Matta Matka Indian Matka Satta Matka Dpboss Matka boss otg➒➌➍➑➑➌➏➑➑➐ Satta Matta Matka Indian Matka Satta Matka Dpboss Matka boss otg
➒➌➍➑➑➌➏➑➑➐ Satta Matta Matka Indian Matka Satta Matka Dpboss Matka boss otg
⑨③④⑧⑧③⑥⑧⑧⑦Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
 
Satta Matka Dp Boss Matka Matka guessing Indian matka Kalyan Matka➐➑➎➎➑⓿➊➒➌➎
Satta Matka Dp Boss Matka Matka guessing Indian matka Kalyan Matka➐➑➎➎➑⓿➊➒➌➎Satta Matka Dp Boss Matka Matka guessing Indian matka Kalyan Matka➐➑➎➎➑⓿➊➒➌➎
Satta Matka Dp Boss Matka Matka guessing Indian matka Kalyan Matka➐➑➎➎➑⓿➊➒➌➎
➐➑➎➎➑⓿➊➒➌➎ SATTA MATKA DP BOSS KALYAN RESULT
 
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart Madhur Matka...
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan  Chart Madhur Matka...➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan  Chart Madhur Matka...
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart Madhur Matka...
⑨③④⑧⑧③⑥⑧⑧⑦Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
 
DP boss matka matka kalyan chart sattamatka
DP boss matka matka kalyan chart sattamatkaDP boss matka matka kalyan chart sattamatka
DP boss matka matka kalyan chart sattamatka
SATTA MATKA MATKA INDIA KALYAN CHART
 
@Call @Girls Kolkata 0000000000 Thise Payal roy From Us
@Call @Girls Kolkata 0000000000 Thise Payal roy From Us@Call @Girls Kolkata 0000000000 Thise Payal roy From Us
@Call @Girls Kolkata 0000000000 Thise Payal roy From Us
Gurgaon call Girl Service
 
SattaMatka143 matka fix ank Dp boss matka matka Indian
SattaMatka143 matka fix ank Dp boss matka matka IndianSattaMatka143 matka fix ank Dp boss matka matka Indian
SattaMatka143 matka fix ank Dp boss matka matka Indian
➐➑➎➎➑⓿➊➒➌➎ SATTA MATKA DP BOSS KALYAN RESULT
 
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
⑨③④⑧⑧③⑥⑧⑧⑦Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
 
Cobra 200mg tablet at Rs 150/strip in Nagpur | ID
Cobra 200mg tablet at Rs 150/strip in Nagpur | IDCobra 200mg tablet at Rs 150/strip in Nagpur | ID
Cobra 200mg tablet at Rs 150/strip in Nagpur | ID
yAshika sharman06
 
Chennai @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
Chennai @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My homeChennai @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
Chennai @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
mriyagarg453
 
ASDJGfkhgisafhgfiljiKHFLIUhfliHFIUgfgUHU
ASDJGfkhgisafhgfiljiKHFLIUhfliHFIUgfgUHUASDJGfkhgisafhgfiljiKHFLIUhfliHFIUgfgUHU
ASDJGfkhgisafhgfiljiKHFLIUhfliHFIUgfgUHU
sjcitbrac
 
Aligarh @Call @Girls Whatsapp 000//00000 With Best And No 1
Aligarh @Call @Girls Whatsapp 000//00000 With Best And No 1Aligarh @Call @Girls Whatsapp 000//00000 With Best And No 1
Aligarh @Call @Girls Whatsapp 000//00000 With Best And No 1
arvindkumarji156
 

Recently uploaded (20)

Matka India Sattamatka Dp boss Today matka
Matka India Sattamatka Dp boss Today matkaMatka India Sattamatka Dp boss Today matka
Matka India Sattamatka Dp boss Today matka
 
@Call @Girls in Pune 🚒 0000000000 🚒 Tanu Sharma Best High Class Pune Available
@Call @Girls in Pune 🚒 0000000000 🚒 Tanu Sharma Best High Class Pune Available@Call @Girls in Pune 🚒 0000000000 🚒 Tanu Sharma Best High Class Pune Available
@Call @Girls in Pune 🚒 0000000000 🚒 Tanu Sharma Best High Class Pune Available
 
Daryaganj @ℂall @Girls ꧁❤ 9711199012 ❤꧂Fabulous sonam Mehra Top Model Safe
Daryaganj @ℂall @Girls ꧁❤ 9711199012 ❤꧂Fabulous sonam Mehra Top Model SafeDaryaganj @ℂall @Girls ꧁❤ 9711199012 ❤꧂Fabulous sonam Mehra Top Model Safe
Daryaganj @ℂall @Girls ꧁❤ 9711199012 ❤꧂Fabulous sonam Mehra Top Model Safe
 
Satta Matka Matka king DP boss Indian Matka Matka Kalyan
Satta Matka Matka king DP boss Indian Matka Matka KalyanSatta Matka Matka king DP boss Indian Matka Matka Kalyan
Satta Matka Matka king DP boss Indian Matka Matka Kalyan
 
Chandigarh @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
Chandigarh @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My homeChandigarh @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
Chandigarh @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
 
Common Types of Dementia 8F who notes progressive memory loss
Common Types of Dementia 8F who notes progressive memory lossCommon Types of Dementia 8F who notes progressive memory loss
Common Types of Dementia 8F who notes progressive memory loss
 
Preventing Dementia - The Basics Millions of results on Google…
Preventing Dementia - The Basics Millions of results on Google…Preventing Dementia - The Basics Millions of results on Google…
Preventing Dementia - The Basics Millions of results on Google…
 
202254.com《长相思第二季》在线观看,最新电视剧《长相思第二季》在线播放,长相思第二季今天开播了,全网最高清电视剧免费播放
202254.com《长相思第二季》在线观看,最新电视剧《长相思第二季》在线播放,长相思第二季今天开播了,全网最高清电视剧免费播放202254.com《长相思第二季》在线观看,最新电视剧《长相思第二季》在线播放,长相思第二季今天开播了,全网最高清电视剧免费播放
202254.com《长相思第二季》在线观看,最新电视剧《长相思第二季》在线播放,长相思第二季今天开播了,全网最高清电视剧免费播放
 
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart Madhur Matka...
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan  Chart Madhur Matka...➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan  Chart Madhur Matka...
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart Madhur Matka...
 
➒➌➍➑➑➌➏➑➑➐ Satta Matta Matka Indian Matka Satta Matka Dpboss Matka boss otg
➒➌➍➑➑➌➏➑➑➐ Satta Matta Matka Indian Matka Satta Matka Dpboss Matka boss otg➒➌➍➑➑➌➏➑➑➐ Satta Matta Matka Indian Matka Satta Matka Dpboss Matka boss otg
➒➌➍➑➑➌➏➑➑➐ Satta Matta Matka Indian Matka Satta Matka Dpboss Matka boss otg
 
Satta Matka Dp Boss Matka Matka guessing Indian matka Kalyan Matka➐➑➎➎➑⓿➊➒➌➎
Satta Matka Dp Boss Matka Matka guessing Indian matka Kalyan Matka➐➑➎➎➑⓿➊➒➌➎Satta Matka Dp Boss Matka Matka guessing Indian matka Kalyan Matka➐➑➎➎➑⓿➊➒➌➎
Satta Matka Dp Boss Matka Matka guessing Indian matka Kalyan Matka➐➑➎➎➑⓿➊➒➌➎
 
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart Madhur Matka...
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan  Chart Madhur Matka...➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan  Chart Madhur Matka...
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart Madhur Matka...
 
DP boss matka matka kalyan chart sattamatka
DP boss matka matka kalyan chart sattamatkaDP boss matka matka kalyan chart sattamatka
DP boss matka matka kalyan chart sattamatka
 
@Call @Girls Kolkata 0000000000 Thise Payal roy From Us
@Call @Girls Kolkata 0000000000 Thise Payal roy From Us@Call @Girls Kolkata 0000000000 Thise Payal roy From Us
@Call @Girls Kolkata 0000000000 Thise Payal roy From Us
 
SattaMatka143 matka fix ank Dp boss matka matka Indian
SattaMatka143 matka fix ank Dp boss matka matka IndianSattaMatka143 matka fix ank Dp boss matka matka Indian
SattaMatka143 matka fix ank Dp boss matka matka Indian
 
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
➒➌➍➑➑➌➏➑➑➐ Satta Matka Dpboss Kalyan Matka Results Kalyan Chart
 
Cobra 200mg tablet at Rs 150/strip in Nagpur | ID
Cobra 200mg tablet at Rs 150/strip in Nagpur | IDCobra 200mg tablet at Rs 150/strip in Nagpur | ID
Cobra 200mg tablet at Rs 150/strip in Nagpur | ID
 
Chennai @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
Chennai @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My homeChennai @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
Chennai @Call @Girls 0000000000 Thise Is Komal Verma Meet Me At My home
 
ASDJGfkhgisafhgfiljiKHFLIUhfliHFIUgfgUHU
ASDJGfkhgisafhgfiljiKHFLIUhfliHFIUgfgUHUASDJGfkhgisafhgfiljiKHFLIUhfliHFIUgfgUHU
ASDJGfkhgisafhgfiljiKHFLIUhfliHFIUgfgUHU
 
Aligarh @Call @Girls Whatsapp 000//00000 With Best And No 1
Aligarh @Call @Girls Whatsapp 000//00000 With Best And No 1Aligarh @Call @Girls Whatsapp 000//00000 With Best And No 1
Aligarh @Call @Girls Whatsapp 000//00000 With Best And No 1
 

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