Operating Systems · Lecture Notes

Chapter 7: Deadlocks

If two threads try to acquire two locks in opposite orders, both may wait forever. Because neither runs, neither releases the lock it holds. This situation is called a deadlock. A deadlocked program raises no error and does not crash; it simply stops. Worse, it often appears only under one particular interleaving and can slip through testing. The chapter begins with the notion of a resource and the four conditions for deadlock. It then models deadlock with graphs and works through the four ways of coping with it in turn: ignoring it, detecting and recovering, avoiding, and preventing. Cycle search and a matrix-based algorithm are worked out step by step for detection, and safe states and the banker's algorithm for avoidance. The final sections cover livelock, starvation, concurrency bugs that are not deadlocks, and how deadlocks are found in Java programs.

Learning outcomes

Definition and resources
Define deadlock; distinguish preemptable from nonpreemptable resources and describe the request–use–release cycle.
Four conditions
Demonstrate mutual exclusion, hold and wait, no preemption, and circular wait on an example.
Modeling
Draw resource-allocation and wait-for graphs, and say when a cycle in the graph means deadlock.
Detection and recovery
Execute the cycle-search and matrix-based detection algorithms by hand; compare recovery by preemption, rollback, and termination.
Avoidance
Tell safe states from unsafe ones; use the banker's algorithm to decide whether a request should be granted.
Prevention and practice
Recognize lock ordering, two-phase locking, livelock, and starvation; find a deadlock in Java with jstack.

7.1Deadlock and resources

Processes that run concurrently share resources: a printer, a file, a database record, the lock that protects a data structure in memory. The usual way to regulate sharing is to make the other processes wait until the process using the resource has finished. Waiting is normally harmless; the waiting process resumes when its turn comes. But if the waiting forms a ring, the turn never comes. This section gives the definition of deadlock, the kinds of resources involved, and the smallest possible example.

7.1.1What is deadlock?

Consider the simplest case. Process P1 holds resource R1 and waits for R2. Process P2 holds R2 and waits for R1. P1 cannot make progress because it cannot get R2, and it does not release R1. For the same reason P2 does not release R2. Both processes are blocked. The only event that could wake them is the other releasing its resource, and that event will never happen.

Definition 7.1

A set of processes is deadlocked if every process in the set is waiting for an event that only another process in the set can trigger. The awaited event is usually the release of a resource.

The phrase “only another process in the set” in the definition matters. If someone outside can rescue the waiting process, for example if the process holding the resource lies outside the set and will eventually finish, there is no deadlock, only a long wait. In a deadlock the rescuer is inside the set, and since everyone in the set is waiting, the rescuer never runs.

Everyday life offers similar situations. At an intersection that four cars enter at the same time, each car blocks the one on its right, and none can move (gridlock). Two trains approaching each other on a single track also wait for each other. Figure 7.1 shows the intersection example.

ABCDqueuequeue
Figure 7.1: Deadlock at an intersection. Four cars hold the four squares of the intersection, and each waits for the square held by the next. The queues behind them mean that none can back up, either.

Deadlocked processes burn no CPU time, because they are blocked. The real damage is that the resources they hold stay unusable forever. Other processes that want those resources start to wait as well, and the deadlock spreads. The problem is not specific to operating systems: database transactions, multithreaded applications, and distributed systems also deadlock. In these notes the word “process” includes threads; everything said here holds for both.

7.1.2Preemptable and nonpreemptable resources

Deadlock is about resources. A resource is anything a process must acquire in order to use it: a hardware device, a region of memory, a file, a lock, a database record. For deadlock purposes resources fall into two classes.

Definition 7.2

A preemptable resource can be taken away from its owner without harm and given back later. A nonpreemptable resource, in contrast, breaks the work in progress if it is taken from its owner; only the owner can release it, of its own accord.

The CPU is a preemptable resource. The scheduler stops the running process, saves its registers, and gives the CPU to another process; the process later continues where it left off. Main memory is preemptable too: a page can be written to disk and its frame given to another process, and the page is loaded back when needed. For such resources, even if a ring of waiting forms, the operating system can break it by reallocating the resource.

A Blu-ray disc that is half written is not preemptable: interrupting the burn and handing the drive to another process ruins the disc. A job being printed is similar; pages of another job would be interleaved with it. Data protected by a mutex or semaphore is left in an inconsistent intermediate state if the lock is taken by force. Deadlocks concern nonpreemptable resources of this kind. Table 7.1 lists common resources by type.

Table 7.1: Classification of resources from the deadlock point of view.
ResourceNumber of instancesTypeNote
CPU coremanypreemptablechanges hands on a timer interrupt
Memory pagemanypreemptablereclaimed by swapping or paging
Mutex, semaphore, file lock1nonpreemptableonly the owner releases it
Database row lock1nonpreemptable**released if the transaction is rolled back

The “number of instances” column of the table also matters. A resource type may have several identical instances. If the system has two tape drives and a process asks for “a tape drive,” it makes no difference which of the two it gets. Instances are identical if a request can be satisfied by any instance of the type. In general, resource type Ri has Wi instances. The number of instances directly affects how deadlock is detected.

Common mistake

Thinking that a database record lock is preemptable because the database resolves a deadlock by aborting a transaction. Aborting is not the same as forcibly taking the lock and giving it to someone else; all the changes of the transaction are undone and the transaction starts over. The resource is not preempted, work is lost. That is why the table marks it with an asterisk.

7.1.3The resource-use cycle

A process always uses a resource in the same three steps:

  1. Request. If the resource is free, it is given to the process. If not, the process blocks and is woken when the resource becomes free. In some systems the process instead receives an error code and retries a little later.
  2. Use. The process operates on the resource: it prints on the printer, writes to the file, updates the protected data.
  3. Release. The resource becomes free; one of the processes waiting for it is woken.

The operating system keeps a table recording which resource is assigned to whom and who is waiting for which resource. Deadlock detection works from the information in this table. Requesting and releasing are usually system calls or library functions; Table 7.2 shows the best-known pairs.

Table 7.2: Counterparts of the request and release operations.
RequestRelease
open()close()
malloc() / mmap()free() / munmap()
pthread_mutex_lock()pthread_mutex_unlock()
sem_wait() (down)sem_post() (up)
1. Request2. Use3. Releasegrantedbusy →blocked
Figure 7.2: The resource-use cycle. If the resource is busy, the process blocks at the request step; when the resource is released, it wakes and moves on to the use step.

7.1.4Same order and reverse order

Suppose user processes protect their resources with semaphores. Let each resource correspond to a binary semaphore: down before accessing the resource, up when finished. With one process or one resource there is no problem. With two processes and two resources, the order in which the resources are acquired decides the outcome. The following two processes acquire the resources in the same order:

void process_A(void) {
  down(&resource_1);
  down(&resource_2);
  use_both_resources();
  up(&resource_2);
  up(&resource_1);
}
void process_B(void) {
  down(&resource_1);
  down(&resource_2);
  use_both_resources();
  up(&resource_2);
  up(&resource_1);
}

This code does not deadlock. Both processes ask for resource_1 first. One gets it and the other waits. The process that has resource_1 acquires resource_2 without trouble, because the only other process that could want it is still waiting in front of resource_1. When it finishes and releases both resources, the waiting process continues.

Now reverse the order in B:

void process_A(void) {
  down(&resource_1);
  down(&resource_2);
  use_both_resources();
  up(&resource_2);
  up(&resource_1);
}
void process_B(void) {
  down(&resource_2);  /* reverse order */
  down(&resource_1);
  use_both_resources();
  up(&resource_1);
  up(&resource_2);
}

In this version deadlock is possible. If A takes resource_1 and B takes resource_2, each waits for what the other holds. The order of release does not matter; what counts is the order of acquisition, that is, of the down calls. From the programmer's point of view the two versions are almost identical. Swapping two lines turns a program that never deadlocks into one that deadlocks now and then.

7.1.5Code trace: acquiring in reverse order

An abbreviated form of the reverse-order code follows. Both binary semaphores start at 1, so both resources are free.

semaphore r1 = 1, r2 = 1;
void A(void) {
  down(&r1);
  down(&r2);
  use_both();
  up(&r2); up(&r1);
}
void B(void) {
  down(&r2);
  down(&r1);
  use_both();
  up(&r1); up(&r2);
}

Suppose that on a single CPU the scheduler picks this sequence: A's first down, B's first down, A's second down, B's second down. Table 7.3 shows the state of the semaphores and processes at each step, and Figure 7.3 shows the graph for the same steps. In the graph a circle stands for a process and a square for a resource. A solid arrow from a resource to a process means “this resource belongs to this process,” and a dashed arrow from a process to a resource means “this process is waiting for this resource.”

Table 7.3: Trace of acquisition in reverse order.
StepEventr1r2AB
0start11readyready
1A: down(&r1)01holds r1ready
2B: down(&r2)00holds r1holds r2
3B: down(&r1)00holds r1blocked (r1)
4A: down(&r2)00blocked (r2)blocked (r1)
ABr1r2 ABr1r2
ABr1r2 ABr1r2cycle: A → r2 → B → r1 → A
Figure 7.3: Acquisition in reverse order. (a) A takes r1. (b) The scheduler switches to B; B takes r2. (c) B requests r1 and blocks. (d) A requests r2 and blocks too: the cycle A → r2 → B → r1 → A has formed in the graph.

After the fourth step both processes are blocked, and neither can reach its up lines. The cycle in the graph is the visual mark of deadlock. The deadlock does not occur on every run. If A finishes both down calls before B starts, B waits at its first down and continues when A is done. Deadlock occurs only if both processes execute their first down before the other's second down. Because this window is narrow, the bug is rarely seen in testing and shows up when the system is under load.

Common mistake

Running the program a few times, seeing no deadlock, and concluding that the code is correct. A deadlock depends on a particular timing; it may not show up even once in a thousand runs. Correctness is shown by considering every possible ordering. In practice the most reliable approach is to acquire locks in the same order everywhere.

7.2The four conditions for deadlock

What made deadlock possible in the reverse-order example? The resources could not be shared, the processes held one resource while waiting for another, nobody could take a resource back by force, and the waiting formed a ring. In 1971 Coffman, Elphick, and Shoshani showed that these four properties are necessary for deadlock.

7.2.1The Coffman conditions

Theorem 7.1 (The four conditions for deadlock)

For deadlock to occur, the following four conditions must hold at the same time:

  1. Mutual exclusion: each resource is either assigned to exactly one process or free; it cannot be shared at the same time.
  2. Hold and wait: a process holding at least one resource requests new resources held by others and waits for them.
  3. No preemption: a resource that has been granted cannot be taken back by force; only the process holding it releases it, of its own accord.
  4. Circular wait: T0 waits for a resource held by T1; T1 for one held by T2; …; and Tn for one held by T0.
T0R2waitsheld byT1R3waitsheld byT2R1waitsR1 → T0 (holder): the ring closes
Figure 7.4: Circular wait. T0 holds R1 and waits for R2; T1 holds R2 and waits for R3; T2 holds R3 and waits for R1. The last arrow closes the ring.

That the conditions are “jointly necessary” means that deadlock is impossible in a system where even one of them is missing. If a resource can be shared, nobody waits for it. If no process waits while holding a resource, no ring can be built. If resources can be taken back, the ring can be broken. And if no ring ever forms, every waiting process eventually gets its turn. The prevention strategy rests on exactly this observation: make one of the four conditions structurally impossible.

The four conditions are not of the same nature. The first three are the system's policy: whether resources are shared, how processes request resources, and whether resources can be taken back are fixed at design time. When these three policies hold, deadlock can occur, but need not. The fourth condition is the system's current state: depending on the order in which processes request resources, the ring either forms or does not. If there is only one instance of each resource type, the four conditions are also sufficient: if all four hold, the system is deadlocked. With multiple-instance resources the sufficiency disappears: another instance of a resource in the cycle may be held by a process outside the cycle.

Common mistake

Using the conditions interchangeably. “No preemption” means that a resource cannot be taken back by force; “hold and wait” means that a process holds one resource while waiting for another. Requiring a process to release what it holds before making a new request breaks hold and wait. Having the operating system take a held resource by force breaks no preemption.

7.2.2The intersection example

To make the four conditions concrete, return to the intersection. Its four squares are four nonpreemptable resources, and the cars are the processes. Figure 7.5 marks the conditions one by one.

ABCDqueuequeueone car per square at a time ABCDqueuequeue
ABCDqueuequeueno car can back up ABCDqueuequeue
Figure 7.5: The four conditions at the intersection. (a) Mutual exclusion: only one car can be in a square at a time. (b) Hold and wait: each car holds its square while waiting for the square ahead. (c) No preemption: there is a queue behind, so no car can back up. (d) Circular wait: A → B → C → D → A.
  1. Mutual exclusion. Two cars do not fit in the same square. A square is either empty or belongs to a single car.
  2. Hold and wait. Each car holds the square it has entered and waits for the square ahead in order to move on.
  3. No preemption. There is a queue behind each car; none of them can back up and vacate the square.
  4. Circular wait. A waits for B's square, B for C's, C for D's, and D for A's. The ring is closed and the traffic is deadlocked.

The remedies in traffic also break one of the conditions. If a traffic officer makes a car back up, no preemption is broken. The rule “do not enter unless the intersection is clear” keeps a car from holding one square while waiting for another, so hold and wait disappears. A traffic light gives the directions turns and keeps the ring from forming. The prevention methods in computer systems correspond to these three ideas.

7.3Modeling deadlock

To talk about deadlock we need a tool that shows at a glance who holds what and who waits for what. The resource-allocation graph that Holt proposed in 1972 serves this purpose. The graph makes it easier to understand how deadlock arises, and it is also the data structure on which the detection algorithms work.

7.3.1The resource-allocation graph

Definition 7.3

A resource-allocation graph is a directed graph with two kinds of nodes. Processes are drawn as circles and resources as squares. An assignment edge R → P from a resource to a process shows that R has been given to P. A request edge P → R from a process to a resource shows that P is waiting for R.

When a request is granted, the request edge turns into an assignment edge, that is, the direction of the arrow is reversed. When the resource is released, the assignment edge is deleted. For a resource type with several instances, one dot per instance is placed inside the square. An assignment edge starts at one of these dots; a request edge goes to the square itself, because the process waits not for a particular instance but for any instance of the type. In these notes request edges are drawn dashed and orange.

AR(a) A holds RBS(b) B requests SCDUT(c) Deadlock: C → U → D → T → C
Figure 7.6: The notation of the resource-allocation graph. (a) Assignment edge from R to A: A holds R. (b) Request edge from B to S: B wants S. (c) C waits for U; U is held by D; D waits for T; T is held by C. The cycle C → U → D → T → C in the graph is a deadlock.

Tanenbaum draws the same model with process nodes. Silberschatz instead calls the nodes threads and labels them with the letter T. There is no difference in meaning between the two notations. In these notes, each example keeps the naming of the source it was taken from.

7.3.2How deadlock arises

Consider three processes (A, B, C) and three resources (R, S, T). Each process requests two resources and releases both:

A          B          C
request R  request S  request T
request S  request T  request R
release R  release S  release T
release S  release T  release R

Suppose the operating system schedules the processes round robin and satisfies requests in the order they arrive. The first requests of the processes arrive in turn, and since all three resources are free, all are satisfied. When the second requests arrive, each process asks for the resource held by the next one. Figure 7.7 shows the six requests and the state of the graph at each step.

ABCRST ABCRST ABCRST
ABCRST ABCRST ABCRSTcycle A→S→B→T→C→R→A
Figure 7.7: How a deadlock forms (Tanenbaum Figure 6-4). (a) A gets R. (b) B gets S. (c) C gets T. (d) A requests S and blocks. (e) B requests T and blocks. (f) C requests R and blocks: the cycle A → S → B → T → C → R → A closes.
  1. A requests R. R is free; the assignment edge R → A is added.
  2. B requests S. S is free; S → B is added.
  3. C requests T. T is free; T → C is added.
  4. A requests S. S is held by B. A blocks; the request edge A → S is added.
  5. B requests T. T is held by C. B blocks; B → T is added.
  6. C requests R. R is held by A. C blocks; C → R is added. The graph now contains the cycle A → S → B → T → C → R → A, and all three processes are deadlocked.

This outcome was not inevitable. The scheduler could have picked a different order. For example, if it had run A until A had made both requests and released its resources, then B, then C, no request would ever have waited. Parallelism would have been lost, but there would have been no deadlock. Deadlock depends on the order of the requests.

7.3.3How deadlock can be prevented

If the operating system knew in advance that granting a request would lead to deadlock, it could prevent the deadlock by making the dangerous request wait. In the same example, suppose the operating system suspends B's requests for a while, that is, does not schedule B. Only A and C run. Figure 7.8 follows this ordering.

ABCRST ABCRST ABCRST
ABCRST ABCRST ABCRST
Figure 7.8: No deadlock when B is postponed (Tanenbaum Figure 6-4). (a) A gets R. (b) C gets T. (c) A gets S. (d) C requests R and blocks; there is no cycle. (e) A releases R; R is given to C. (f) A releases S and finishes; now B can run.
  1. A gets R; C gets T. Both resources are free.
  2. A gets S. S is free, because B has not requested it yet.
  3. C requests R. R is held by A; C blocks. The graph has a request edge but no cycle. A is waiting for nothing and can proceed.
  4. A releases R. R is given to the waiting C, and C proceeds.
  5. A releases S and finishes. Now B is run. B gets S, and gets T when C finishes. There is no deadlock.

What the operating system does here is the essence of the avoidance strategy: which request should be postponed? To choose the request to postpone, one must know how many resources each process may ask for. The banker's algorithm uses this information.

7.3.4Resources with multiple instances

In the examples so far each resource type had a single instance. Silberschatz's classic example also includes multiple-instance types. The resource sets are as follows: R1 has one instance, R2 two, R3 one, and R4 three. The state of the three threads is as follows:

  • T1 holds one instance of R2 and waits for R1.
  • T2 holds R1 and one instance of R2, and waits for R3.
  • T3 holds R3.
R1R3T1T2T3R2R4
Figure 7.9: An allocation graph with multiple-instance resources (Silberschatz Figure 8.4). An assignment edge starts from a dot in the square, that is, from a particular instance; a request edge goes to the square itself. All three instances of R4 are idle.

The graph has no cycle. Since T3 waits for nothing, it finishes and releases R3. R3 is given to T2; T2 also finishes and releases R1 and its instance of R2. R1 is given to T1, and T1 finishes as well. The finishing order is T3, T2, T1. If there is no cycle, there is no deadlock; this rule is independent of the number of instances.

7.3.5Cycles and deadlock

Add a single request to the same situation: T3 asks for an instance of R2. Both instances of R2 are in use (one by T1, one by T2), so T3 blocks. This one request edge creates two cycles in the graph:

  • Cycle 1: T1 → R1 → T2 → R3 → T3 → R2 → T1.
  • Cycle 2: T2 → R3 → T3 → R2 → T2.
R1R3T1T2T3R2R4 R1R3T1T2T3R2R4T1, T2, T3 deadlocked
Figure 7.10: A deadlocked multiple-instance graph (Silberschatz Figure 8.5). (a) T3 requests an instance of R2; both instances are in use and T3 blocks. (b) Two cycles form; the owners of both instances of R2 are on the cycles. T1, T2, and T3 are deadlocked.

In this case there is no rescuer. T3 waits for one of the instances of R2 to be released, but the owners of both instances (T1 and T2) are on the cycle. T2 waits for R3, which T3 holds, and T1 waits for R1, which T2 holds. Every process on the cycle waits for another process on the cycle, and there is no one outside to release a resource. All three threads are deadlocked.

7.3.6A cycle without deadlock

With multiple-instance resources a cycle does not always mean deadlock. In Silberschatz's second example, R1 and R2 have two instances each. The two instances of R1 are held by T2 and T3, and the two instances of R2 by T1 and T4. T1 requests an instance of R1, and T3 an instance of R2. The graph contains the cycle T1 → R1 → T3 → R2 → T1.

T1R1T2T3R2T4 T1R1T2T3R2T4
Figure 7.11: A cycle but no deadlock (Silberschatz Figure 8.6). (a) The cycle T1 → R1 → T3 → R2 → T1; T2 and T4 are outside the cycle and wait for nothing. (b) T4 finishes and releases its instance of R2; the instance is given to T3, and the cycle is broken.

The difference lies in the processes outside the cycle. T2 and T4 wait for nothing; they finish and release their instances. The instance of R2 released by T4 is given to T3, and the cycle is broken. The instance of R1 released by T2 can also go to T1. In the end everyone finishes; the system was never deadlocked.

Example 7.1

R1 has two instances, and R2 and R3 have one each. P1 holds R2 and requests R1. P2 holds one instance of R1 and requests R3. P3 holds R3 and requests R2. P4 holds the other instance of R1 and requests nothing. Is there a cycle in the graph? Is the system deadlocked?

  1. The cycle. P1 → R1 → P2 → R3 → P3 → R2 → P1 is a cycle. If the resources had a single instance each, this would be a certain deadlock.
  2. An instance outside the cycle. The second instance of R1 is held by P4, which is not on the cycle. P4 waits for nothing, finishes, and releases its instance of R1.
  3. A chain of completions. P1's request for R1 is satisfied; P1 finishes and releases R1 and R2. P3 gets R2 and finishes, freeing R2 and R3. P2 gets R3 and finishes.
  4. Result. The finishing order is P4, P1, P3, P2. Because everyone can finish, there is no deadlock.

7.3.7The cycle rule

The conclusions from the examples are summarized in Table 7.4. If there is no cycle, there is no deadlock under any circumstances. If there is a cycle, the outcome depends on the number of instances.

Table 7.4: The relation between a cycle in the allocation graph and deadlock.
GraphOne instance of every typeSeveral instances of some types
No cycleno deadlockno deadlock
Cycledeadlock (cycle ⇔ deadlock)deadlock possible; a cycle is necessary but not sufficient
Theorem 7.2 (The cycle rule)

If the resource-allocation graph has no cycle, the system is not deadlocked. If every resource type has a single instance, a cycle is both a necessary and a sufficient condition for deadlock, and the processes on the cycle are deadlocked. If some types have several instances, a cycle is necessary but not sufficient.

In the single-instance case every resource on the cycle has exactly one holder, and that holder waits for another resource on the cycle. Since the only process that could release the resource is itself waiting, the resource never becomes free, and none of the processes on the cycle can proceed. In the multiple-instance case another instance of a resource on the cycle may be held by a process outside the cycle. When that process finishes and releases the instance, the request on the cycle is satisfied. That is why a cycle does not guarantee deadlock.

For single-instance resources, depth-first search is enough to find the cycle, and its cost is O(V + E) (V nodes, E edges). For multiple-instance resources a cycle is only a warning. To decide for certain, one asks, using the allocation and request matrices, “can everyone finish in some order?” The theorem is also consistent with the four conditions: circular wait corresponds to a graph that contains a cycle.

7.3.8The wait-for graph

If every resource type has a single instance, the allocation graph can be simplified further. Because a resource has a single holder, the information “Pi waits for R and R is held by Pj” simply means “Pi waits for Pj.”

Definition 7.4

A wait-for graph is a directed graph consisting only of process nodes. Every path Pi → R → Pj in the allocation graph is collapsed into a single edge Pi → Pj; the resource nodes are removed.

Figure 7.12 shows the transformation on an example with four processes. P1 holds R1 and requests R2. P2 holds R2 and requests R3. P3 holds R3 and requests R1. P4 holds R4 and requests R2.

P1P2P3P4R2R3R1R4
P1P2P3P4cycle: P1→P2→P3→P1P4 is not in the cycle, butit waits for P2, so it toowaits forever
Figure 7.12: From the allocation graph to the wait-for graph. Top: the allocation graph with single-instance resources; bottom: the wait-for graph after the resource nodes are removed. The cycle P1 → P2 → P3 → P1 is a deadlock; P4 is not on the cycle, but because it waits for P2 it also waits forever.

The edges are obtained like this: P1 waits for R2 and R2 is held by P2, hence P1 → P2. In the same way P2 → P3, P3 → P1, and P4 → P2 are found. A cycle appears in the wait-for graph if and only if there is a deadlock. The operating system maintains this graph and runs a cycle-searching algorithm at intervals. Silberschatz gives the cost of this scan as O(n2) (n: number of processes).

The wait-for graph can be used only when every type has a single instance; for a multiple-instance type the “holder of R” is not a single process. Databases use this method widely: PostgreSQL and MySQL InnoDB maintain a wait-for graph for row locks and abort one of the transactions when they find a cycle.

Common mistake

Assuming that processes not on the cycle can always proceed. In the wait-for graph P4 is not on the cycle, but the P2 it waits for is. Since P2 will never finish, P4 can never proceed either. The deadlocked set is only the processes on the cycle; processes connected to the cycle by a path are indirect victims of the deadlock.

7.4Strategies for coping

There are four ways to cope with deadlock. They differ in the following questions: Does the system allow deadlock at all? When is the decision made: at design time, at run time, or after the deadlock has occurred? What information does the decision need?

7.4.1Four strategies

  1. Ignoring it. Also called the “ostrich algorithm.” If deadlock is rare and prevention is expensive, the problem is ignored; if a deadlock occurs, the system or the process is restarted.
  2. Detection and recovery. A reactive approach. Deadlock is allowed; the system checks at intervals whether a deadlock has occurred and, if it finds one, resolves it by preempting resources, rolling back, or terminating.
  3. Dynamic avoidance. A proactive approach that decides at run time. A request that would put the system into an unsafe state is postponed. The banker's algorithm is an example. It requires that the maximum need of every process be known in advance.
  4. Prevention. A proactive approach that decides at design time. At least one of the four conditions is made structurally impossible; lock ordering is the best-known example.

“Recovery” is not listed as a separate strategy because recovery is the second half of detection: first the deadlock is found, then it is resolved. The difference between avoidance and prevention is also often confused. Prevention removes one of the conditions for deadlock from the system altogether; since the condition can never be met, deadlock is impossible. Avoidance, on the other hand, allows all four conditions, but at every request it computes where the state is heading and makes dangerous requests wait.

7.4.2The ostrich algorithm

The simplest strategy is to do nothing. It is named after the ostrich, which is believed to bury its head in the sand in the face of danger. If a deadlock occurs, the user or administrator kills the stuck process and, if necessary, restarts the system.

"Deadlock? What deadlock?"
Figure 7.13: The ostrich algorithm: ignoring the problem.

Although it looks irresponsible at first sight, this choice is an engineering trade-off. If a deadlock happens once a year while crashes and hardware faults are far more frequent, costly and restrictive precautions are not worth it. An avoidance algorithm that runs at every request slows down the whole system, and rules imposed on resource requests make the programmer's job harder.

General-purpose operating systems such as Linux, Windows, and macOS apply this approach to user processes' locks, file locks, and pipe waits. The responsibility lies with the application developer. Inside itself, however, the operating system does take precautions against deadlock: locks in the kernel are acquired in a documented order, and the lockdep tool in Linux checks that order. In real-time and safety-critical systems the ostrich approach is unacceptable; flight-control software cannot be designed on the principle that it is “restarted now and then.”

The ostrich approach is not a middle path between detection and avoidance. It does neither; it merely compares the probability and cost of deadlock with the cost of prevention.

7.5Detection and recovery

In the detection-and-recovery strategy the system places no restriction on resource requests. Requests are satisfied as they arrive, and if the resource is not free the process is made to wait. From time to time the system runs an algorithm to check whether a deadlock has occurred. The algorithm differs depending on whether the resource types have one instance or several.

7.5.1One resource of each type

If every resource type has a single instance, deadlock is the same thing as a cycle in the allocation graph. Tanenbaum's example has seven processes (A–G) and six resources (R–W):

  • A holds R and requests S.
  • B holds nothing but requests T.
  • C holds nothing but requests S.
  • D holds U and requests S and T.
  • E holds T and requests V.
  • F holds W and requests S.
  • G holds V and requests U.
RABCSDTEFUVWG
Figure 7.14: An allocation graph with seven processes and six resources (Tanenbaum Figure 6-5). The highlighted cycle D → T → E → V → G → U → D is the deadlock.

The question is: is the system deadlocked, and if so, which processes are involved? Once the graph is drawn, the answer can be found by eye. D → T → E → V → G → U → D is a cycle; D, E, and G are deadlocked. A, C, and F are not deadlocked. S is free; one of the three takes S, finishes and releases it, and then another takes it. B's case is different: B is not on the cycle, but because it waits for T, which is on the cycle, it cannot proceed either. In this small graph the eye is enough. For a graph with hundreds of nodes a systematic algorithm is needed.

7.5.2The cycle-search algorithm

The algorithm given by Tanenbaum takes each node of the graph in turn as a starting point and proceeds depth-first from it. The path traversed is kept in a list L. If a node is added to L a second time, a cycle has been found.

  1. For each node N in the graph, perform steps 2–6 starting from N.
  2. Make L the empty list; treat all edges as unmarked.
  3. Append the current node to the end of L. If the node now appears twice in L, the graph contains a cycle: report the cycle in L and stop.
  4. Is there an unmarked edge leaving the current node? If so, go to step 5; if not, go to step 6.
  5. Pick one of the unmarked edges, mark it, and move to the node it points to; return to step 3.
  6. If we are at the starting node, there is no cycle reachable from N. If not, we are in a dead end: remove the node from L, go back to the previous node, and continue from step 4.

The essence of the algorithm is a depth-first search (DFS) from each node; the list L plays the role of the stack. Because this simple version restarts from every node, it takes O(V · (V + E)) time in the worst case. The version that colors the nodes with three colors runs in a single pass in O(V + E). In the output, the part of L after the repeated node is the cycle, and the processes in it are deadlocked.

When step 6 says “go back to the previous node,” that node is already in L. That is why we continue from step 4, not step 3; going to step 3 would add the node a second time and report a false cycle. Tanenbaum's text says briefly “go to step 3” at this point; what is meant is to look at the node's outgoing edges without adding it again.

7.5.3Cycle search step by step

Let us run the algorithm on the graph of Figure 7.14. The starting nodes are chosen in the order of the figure, that is, left to right and top to bottom: R, A, B, C, S, D, T, E, F, U, V, W, G. If several edges leave a node, the choice is arbitrary; here, from D the edge to S is chosen first, then the edge to T. Table 7.5 gives the state of L at each step.

Table 7.5: Trace of the cycle-search algorithm.
StartEventL
RR is added; the only exit is R → A[R]
RA is added; A → S[R, A]
RS is added; no edge leaves S[R, A, S]
Rdead end: S is removed, back to A; A has no unmarked edge[R, A]
RA is removed, back to R; R is the start: no cycle from R[R] → []
AA → S, S is a dead end; no cycle from A[A] → [A, S] → []
BB → T → E[B, T, E]
BE → V → G → U[B, T, E, V, G, U]
BU → D; S is tried before T from D[B, T, E, V, G, U, D, S]
BS is a dead end and is removed from L; back to D[B, T, E, V, G, U, D]
BD → T: T is added a second time → cycle[B, T, E, V, G, U, D, T]
RABCSDTEFUVWGL = [R, A, S] RABCSDTEFUVWGL = [B, T, E]
RABCSDTEFUVWGL = [B, T, E, V, G, U, D, S] RABCSDTEFUVWGL = [B, T, E, V, G, U, D, T]
Figure 7.15: Four moments of the cycle search. The orange nodes are in the current list L, and the node with a red outline is the current node. (a) R → A → S reaches a dead end. (b) The search starts from B: B → T → E. (c) After U → D, S is tried. (d) With D → T, T is added a second time: the cycle is T, E, V, G, U, D.

The algorithm stops in the search that starts from B. In the list L = [B, T, E, V, G, U, D, T], T appears twice. The part after the first occurrence of the repeated node, that is, T, E, V, G, U, D, is the cycle. The processes on the cycle are D, E, and G; they are deadlocked. B is at the head of the list but not on the cycle: it lies on a path leading to the cycle. This is the same result we found by inspecting the graph by eye. These results were checked by rerunning the same algorithm in Python.

7.5.4Code trace: colored depth-first search

Restarting from every node does unnecessary work. Colored DFS gives each node a color. A white node has not been visited yet. A gray node is currently on the stack, that is, on the path being followed. A black node has had all its neighbors processed and is finished. An edge to a gray node is called a back edge and shows that there is a cycle. The code below stores the wait-for graph as an adjacency matrix waits[u][v]: if waits[u][v] is 1, u waits for v.

enum { WHITE, GRAY, BLACK };
int color[N];         /* all WHITE */
bool cycle(int u) {
  color[u] = GRAY;    /* on path */
  for (int v = 0; v < N; v++) {
    if (!waits[u][v]) continue;
    if (color[v] == GRAY)
      return true;    /* back edge */
    if (color[v] == WHITE && cycle(v))
      return true;
  }
  color[u] = BLACK;   /* done */
  return false;
}

The logic of the code is as follows. When cycle(u) is called, u is colored gray. Then every v that u waits for is tried. If v is gray, the path has come back onto itself and true is returned. If v is white, cycle(v) is called recursively; if that call finds a cycle, true is passed up. Black neighbors are skipped, because it is already known that no cycle leads out of them. When all neighbors are done, u is colored black and false is returned. Each node is colored gray at most once and each edge is examined once, so the cost is O(V + E). Because finding the edges with an adjacency matrix takes N steps at every node, the actual cost of this code is O(N2).

The graph has five processes, with edges P1 → P2, P2 → P3, P2 → P4, P4 → P5, and P5 → P2. The search starts from P1. Because the for loop tries neighbors in numerical order, from P2 it goes to P3 first and then to P4. Table 7.6 shows the colors at each step, and Figure 7.16 shows the important moments.

Table 7.6: Trace of colored DFS (W: white, G: gray, B: black).
StepEventP1P2P3P4P5Call stack
0startWWWWW—
1cycle(P1): P1 grayGWWWWP1
2P1 → P2 white: cycle(P2)GGWWWP1, P2
3P2 → P3 white: cycle(P3)GGGWWP1, P2, P3
4P3 has no neighbors: black, falseGGBWWP1, P2
5P2 → P4 white: cycle(P4)GGBGWP1, P2, P4
6P4 → P5 white: cycle(P5)GGBGGP1, P2, P4, P5
7P5 → P2: P2 is gray → back edge, trueGGBGGP1, P2, P4, P5
8true is passed up the stackGGBGG—
P1P2P3P4P5white: unvisitedgray: on pathblack: doneP2 tries P3, then P4 P1P2P3P4P5white: unvisitedgray: on pathblack: doneP2 tries P3, then P4
P1P2P3P4P5white: unvisitedgray: on pathblack: doneP2 tries P3, then P4 P1P2P3P4P5white: unvisitedgray: on pathblack: doneP2 tries P3, then P4
Figure 7.16: Colored DFS. (a) At the start all nodes are white. (b) P3 waits for no one and is colored black. (c) On the edge P5 → P2, P2 is gray: a back edge, that is, a cycle. (d) P2, P4, and P5 on the cycle are deadlocked; P1 is not on the cycle but is stuck because it waits for P2.

The cycle is P2 → P4 → P5 → P2, and these three processes are deadlocked. The gray nodes form the path on the stack at that moment; the cycle is the part from the gray node that the back edge points to (P2) up to the top of the stack (P5). P1 is gray too, but because the back edge goes to P2 and not to P1, P1 is not on the cycle. Since P1 waits for P2, it cannot proceed all the same.

Common mistake

Counting an edge to a black neighbor as a cycle too. A black node was finished earlier, and the paths leaving it have been examined and found to be acyclic. An edge to a black node only shows that two paths merge. For example, if there were also an edge P1 → P3, then while P3 is black this edge would not form a cycle. The sign of a cycle is only an edge to a gray node.

7.5.5Several resources of each type: vectors and matrices

If resource types have several instances, searching for cycles is not enough. Instead the allocation and request information is kept in matrices, and the question asked is “can everyone finish in some order?” Let there be n processes and m resource types. The algorithm uses four data structures.

Existing resourcesE = (E₁, E₂, E₃, …, Eₘ)Available resourcesA = (A₁, A₂, A₃, …, Aₘ)Allocation matrix C (row i: what Pi holds)C₁₁ C₁₂ C₁₃ … C₁ₘC₂₁ C₂₂ C₂₃ … C₂ₘ ⋮ ⋮Cₙ₁ Cₙ₂ Cₙ₃ … CₙₘRequest matrix R (row i: what Pi requests)R₁₁ R₁₂ R₁₃ … R₁ₘR₂₁ R₂₂ R₂₃ … R₂ₘ ⋮ ⋮Rₙ₁ Rₙ₂ Rₙ₃ … RₙₘInvariant: Σᵢ Cᵢⱼ + Aⱼ = Eⱼ (for every resource type j)
Figure 7.17: The data structures of the detection algorithm (Tanenbaum Figure 6-6): existing resources E, available resources A, the allocation matrix C, and the request matrix R. For every type j, the held and available instances add up to the number of existing instances.
  • E (existing resources): Ej is the total number of instances of type j in the system.
  • A (available resources): Aj is the number of instances of type j that are free right now.
  • C (allocation matrix): row i of C holds the resources Pi currently holds.
  • R (request matrix): row i of R holds the resources Pi currently requests and is waiting for.

There is an invariant relation among these structures: for every type j, Σi Cij + Aj = Ej. A resource instance is either held by a process or free. Silberschatz gives the same structures under the names Available, Allocation, and Request.

The algorithm compares rows as vectors. For two vectors, X ≤ Y holds if and only if Xj ≤ Yj for every j. For example, (1 0 1 0) ≤ (2 1 0 0) is false: the first two components match, but in the third component 1 > 0. For vectors, “smaller” must hold in every component separately; comparing the sums would give a wrong result.

7.5.6The detection algorithm

The idea of the algorithm is simple. A process whose request can be satisfied by the currently free resources can run and finish. When it finishes it returns all the resources it holds to the free pool; because the pool has grown, another process's request may now be satisfiable. This repeats until no process is left or none of the remaining ones can be satisfied.

A ← available vector
all Pi unmarked
repeat:
  find an unmarked Pi with Ri ≤ A
  if none is found: exit
  A ← A + Ci   /* Pi ends, releases */
  mark Pi
unmarked Pi's are deadlocked
Rᵢ ≤ A ?yesPᵢ finishesA ← A + Cᵢrescan with the new Aif none: stop
Figure 7.18: The detection loop. A process whose request can be met from the available vector finishes and adds what it holds to A; the scan is repeated with the new A. The algorithm stops when no row can be satisfied.

The line “A ← A + Ci” says that the resources held by the finished process return to the free pool. The processes that remain unmarked at the end are deadlocked. This result rests on an optimistic assumption: a process whose request can be satisfied is assumed to finish without asking for more resources. If the process makes a new request before finishing and that request leads to deadlock, the situation will be caught the next time the algorithm runs.

The cost is computed as follows. In each round at most n rows are scanned, and each row comparison has m components. Since each successful round marks one process, there are at most n rounds. The total cost is O(m · n2).

7.5.7A detection example

Example 7.2

There are four resource types: tape drive (Tp), plotter (Pl), scanner (Sc), and CD drive. The existing resources are E = (4 2 3 1) and the available ones A = (2 1 0 0). The allocation and request matrices are as in the figure below (Tanenbaum Figure 6-7). Is the system deadlocked?

C (held)TpPlScCDP10010P22001P30120R (request)TpPlScCDP12001P21010P32100A2100E = (4 2 3 1)
Figure 7.19: The initial state of the detection example: held resources C, requests R, and the available vector A.
  1. Check. The column sums of C are (2 1 3 1); E − (2 1 3 1) = (2 1 0 0) = A. The data are consistent.
  2. P1. R1 = (2 0 0 1) ≤ (2 1 0 0)? In the CD component 1 > 0: there is no free CD. P1 cannot finish for now.
  3. P2. R2 = (1 0 1 0) ≤ (2 1 0 0)? In the scanner component 1 > 0: there is no free scanner.
  4. P3. R3 = (2 1 0 0) ≤ (2 1 0 0) ✓. P3 can run and finish. When it finishes, C3 = (0 1 2 0) comes back: A = (2 1 0 0) + (0 1 2 0) = (2 2 2 0). P3 is marked.
  5. New round, P1. (2 0 0 1) ≤ (2 2 2 0)? CD is still 0; P1 waits again.
  6. P2. (1 0 1 0) ≤ (2 2 2 0) ✓. P2 finishes and C2 = (2 0 0 1) returns: A = (4 2 2 1).
  7. New round, P1. (2 0 0 1) ≤ (4 2 2 1) ✓. P1 finishes and C1 = (0 0 1 0) returns: A = (4 2 3 1) = E.
  8. Result. All processes are marked; the system is not deadlocked. The finishing order found is P3, P2, P1.

In the example the scan starts over from the beginning after each marking. So six comparisons are made in total: three in the first round, two in the second, one in the third. The order found depends on the order in which the algorithm scans the rows, but the deadlock verdict does not change. A process finishing can only enlarge the free pool, never shrink it. So a request that can be satisfied at one stage can still be satisfied at later stages. Whatever order is used for scanning, every process that can be marked is eventually marked. Table 7.7 summarizes how the vector A changes; all the values were recomputed with the algorithm itself in Python.

Table 7.7: Change of the available vector in the detection example.
RoundComparisonResultA afterwards
1P1: (2 0 0 1) ≤ (2 1 0 0)✗ (CD)(2 1 0 0)
1P2: (1 0 1 0) ≤ (2 1 0 0)✗ (scanner)(2 1 0 0)
1P3: (2 1 0 0) ≤ (2 1 0 0)✓ P3 finishes(2 2 2 0)
2P1: (2 0 0 1) ≤ (2 2 2 0)✗ (CD)(2 2 2 0)
2P2: (1 0 1 0) ≤ (2 2 2 0)✓ P2 finishes(4 2 2 1)
3P1: (2 0 0 1) ≤ (4 2 2 1)✓ P1 finishes(4 2 3 1)

7.5.8One request too many: deadlock

Change a single cell in the same situation. Let P3 request a CD as well, in addition to two tape drives and a plotter: R3 = (2 1 0 1). The available vector is still A = (2 1 0 0).

C (held)TpPlScCDP10010P22001P30120R (request)TpPlScCDP12001P21010P32101A2100E = (4 2 3 1)P3 ✗ → P1, P2, P3 deadlocked
Figure 7.20: When P3's request is (2 1 0 1), no row can be satisfied with A = (2 1 0 0); P1, P2, and P3 are deadlocked.
  1. P1 ✗. It needs a CD, and none is free.
  2. P2 ✗. It needs a scanner, and none is free.
  3. P3 ✗. It needs a CD. The only CD is held by P2, and since P2 cannot finish, it will never be freed.

In the first round no row can be satisfied and the algorithm ends immediately. All three processes remain unmarked; all three are deadlocked. Changing a single cell has completely changed the result. The algorithm does not search for cycles, but it yields the deadlocked processes directly; the waiting relation among these processes forms a cycle by itself. P3 waits for the CD held by P2; P2 waits for the scanner held by P1 or the scanners held by P3; and P1 waits for the CD held by P2.

Example 7.3

There are three resource types and E = (5 3 4). The allocations are P1 (1 0 1), P2 (2 1 0), P3 (0 1 2), P4 (1 1 0); the requests are P1 (0 1 0), P2 (1 0 1), P3 (2 0 1), P4 (0 0 2). The rows are scanned in order starting from P1, continuing from where the scan left off. Is the system deadlocked? What would happen if P2's request were (1 1 1)?

  1. Available vector. The allocations sum to (4 3 3); A = (5 3 4) − (4 3 3) = (1 0 1).
  2. P1. (0 1 0) ≤ (1 0 1) fails; there is no free instance of the second type.
  3. P2. (1 0 1) ≤ (1 0 1) ✓ → A = (1 0 1) + (2 1 0) = (3 1 1).
  4. P3. (2 0 1) ≤ (3 1 1) ✓ → A = (3 2 3).
  5. P4. (0 0 2) ≤ (3 2 3) ✓ → A = (4 3 3).
  6. P1. (0 1 0) ≤ (4 3 3) ✓ → A = (5 3 4) = E. Everyone is marked: there is no deadlock.
  7. The change. If P2's request is (1 1 1), then with A = (1 0 1), P1 and P2 ask for the second type (0 free), P3 asks for 2 of the first type (1 available), and P4 asks for 2 of the third type (1 available). In the first round no row can be satisfied; all four processes are deadlocked.

7.5.9When should detection run?

How often to run the detection algorithm is a separate design decision. There are three options:

  • At every request. The algorithm runs after every request that is made to wait. A deadlock is found the moment it forms, together with the request that triggered it. But the CPU cost is high.
  • Periodically. The algorithm runs every k minutes. It is cheap, but a deadlock can go unnoticed for a while, and in the meantime other processes may get caught in the cycle.
  • On a symptom. It runs when CPU utilization drops below a threshold or when a lock wait grows long. Because deadlocked processes use no CPU, low utilization is a good symptom.
checkcheckcheckcheckcheckdeadlock formstime gone unnoticedsmaller k: less delay, more overhead
Figure 7.21: Periodic detection. If a deadlock forms between two checks, it goes unnoticed until the next check. A smaller period k reduces the delay but increases the load.

The right frequency depends on how likely deadlock is and how many processes are affected when it occurs. The overhead of detection is not negligible and is proportional to how often it runs. The cost of recovery, that is, the work that is lost, is also taken into account. PostgreSQL takes a middle path: if a transaction has waited for a lock for deadlock_timeout (1 second by default), it scans the wait-for graph. If it finds a cycle, it aborts one of the transactions and returns the message ERROR: deadlock detected to the client. In this way no scan is made for waits that end by themselves within a short time.

7.5.10Recovering from deadlock

Once a deadlock is found, the cycle has to be broken somehow. There are three ways of breaking it, and none comes free.

Definition 7.5

Deadlock recovery is breaking the cycle by resource preemption, rollback, or process termination. The process chosen to break the cycle is called the victim.

  • Resource preemption. A resource is temporarily taken from its owner and given to another process. For example, the job that a printer is printing is set aside, the printed pages are separated, and the printer is given to another job. This method depends on the nature of the resource; it is often done by hand or is not possible at all.
  • Rollback. Processes record a checkpoint at intervals: they write their memory and resource state to a file. The victim is returned to the last checkpoint before it acquired the contested resource, and the resource is thereby released. The work done after that point is lost. In databases, aborting the transaction is the counterpart.
  • Termination. The crudest method. Either all the processes on the cycle are killed, or they are killed one at a time until the cycle is broken. In the second option the detection algorithm is rerun after each kill. A process from outside the cycle may also be chosen, as long as the resources it releases break the cycle.

The goal in choosing the victim is the lowest cost. The first factors in the cost are the process's priority, how long it has been running, and how much it has left to do. The number of resources it holds and how many more it needs in order to finish also count. One also considers whether the process is interactive or a batch job and whether it can be safely restarted. A compilation can be restarted; a half-finished database update needs care. If the same process is chosen as victim every time, it can never finish, and starvation results. To prevent this, the number of times the process has been rolled back is added to the cost.

Prevention and detection are not recovery methods. And no recovery is free of interruption: every recovery method brings lost work or the cost of rerunning.

7.5.11Recovery step by step

Suppose that, in an example with four processes, the detection algorithm has found the cycle P1 → R2 → P2 → R3 → P3 → R1 → P1. P4 is stuck as well, because it waits for R2. Figure 7.22 shows recovery by terminating one process at a time.

P1P2P3P4R2R3R1R4detected: cycle
P1P2P4R2R3R1R4✕ P3victim: P3requests R3 and R1freed
P1P4R2R3R1R4R2 → P1, then P4P3 is restarted
Figure 7.22: Recovery. (a) The detection algorithm finds the cycle. (b) P3, the process whose loss costs the least work, is chosen as the victim; the R3 it holds is freed. (c) R3 is given to P2; when P2 finishes, R2 goes first to P1 and, when P1 finishes, to P4. P3 is rerun from the beginning or from a checkpoint.
  1. Choosing the victim. The process whose loss costs the least work is P3. P3 is terminated or rolled back to its checkpoint; the R3 it holds is freed.
  2. Detecting again. After P3's edges are removed, no cycle is left in the graph.
  3. A chain of progress. R3 is given to P2, which is waiting for it. P2 finishes and releases R2 and R3. R2 is given to the next waiter, P1; when P1 finishes, P4 gets R2 as well.
  4. Rerunning the victim. P3 is restarted from the beginning or from its last checkpoint. The work lost is the work P3 did after that point.

When processes are terminated one at a time, the detection algorithm is rerun after each victim, and the process stops once the cycle is broken. In this example a single victim was enough.

7.6Deadlock avoidance

The detection strategy lets deadlock happen and then pays the price. The avoidance strategy never lets deadlock happen at all. At every resource request the system asks, “if I grant this request, will deadlock become unavoidable later?” and, if the answer is yes, postpones the request. To answer this question, the maximum amount of resources each process may request must be known in advance.

7.6.1Resource trajectories

The idea of avoidance is seen most clearly in a drawing with two processes. This representation goes back to Dijkstra. Let processes A and B use a printer and a plotter. A uses the printer between instructions I1 and I3 and the plotter between I2 and I4. B uses the plotter between I5 and I7 and the printer between I6 and I8.

The horizontal axis shows the instructions A has executed, the vertical axis those of B. Each moment of the system is a point in the plane. Since there is a single CPU, the trajectory moves only to the right (A is running) or up (B is running); it cannot go diagonally. The two shaded regions are the points where the two processes would use the same resource at the same time. Because of mutual exclusion these regions cannot be entered.

both printerboth plotterunsafeABI1I2I3I4I5I6I7I8A: printer [I1,I3], plotter [I2,I4]pqrst both printerboth plotterunsafeABI1I2I3I4I5I6I7I8A: printer [I1,I3], plotter [I2,I4]pqrstu
Figure 7.23: Resource trajectories of two processes (Tanenbaum Figure 6-8). (a) The trajectory p → q → r → s → t; the red box is the unsafe region. (b) At point t B's request for the plotter is postponed; A runs up to I4 and releases both resources, and then B continues.

Let us follow the trajectory. Between p and q A runs; between q and r B runs. Between r and s A runs again and acquires the printer at I1. Between s and t B advances and is about to request the plotter at I5. The red box is the region where A holds the printer and B holds the plotter. If the trajectory enters this box, both processes are forced to enter one of the shaded regions in order to move right or up. Since that is impossible, deadlock is inevitable. Nobody is blocked yet inside the box, but the outcome is certain. That is why this region is called unsafe.

Avoidance means postponing the request that would send the trajectory into the unsafe region. At point t the operating system makes B's plotter request wait. A runs up to I4 and releases both resources; then B continues, and there is no deadlock. What is critical here is that the operating system knows A will later ask for the plotter. Without this knowledge the request at t would look harmless.

7.6.2Safe and unsafe states

The trajectory picture is limited to two processes and two resources. In the general case avoidance looks at the state of the system. The state is determined by the existing resources E, the available resources A, the allocation matrix C, and the maximum need (Max) of each process.

Definition 7.6

A state is safe if there is a safe sequence ⟨P1, …, Pn⟩ that lets all the processes run to completion in some order, even if every process were to make its maximum request immediately. In the sequence, the remaining need of each Pi does not exceed the sum of the available resources and the resources held by the Pj that precede it in the sequence (j < i). If there is no such sequence, the state is unsafe.

The logic of the definition is the same as that of the detection algorithm; the only difference is the row that is examined. In detection one checks whether the processes' current requests can be satisfied. In avoidance the worst case is assumed: every process is assumed to ask for up to its maximum, and one checks whether its remaining need can be satisfied. The first process in the sequence has its remaining need met from the available resources, finishes, and releases everything. The second process is then satisfied from the enlarged pool, and the chain continues in this way.

safeunsafedeadlock
Figure 7.24: The state space. Deadlocked states are a subset of the unsafe states; safe states are entirely disjoint from deadlock.

An unsafe state is not a deadlocked state. In an unsafe state nobody is permanently blocked yet. If the processes do not make their maximum requests, for example if one releases a resource before making its additional request, everything may go well. The difference is this: in a safe state the system can guarantee that everyone finishes; in an unsafe state it has no such guarantee. The avoidance algorithm always keeps the system in a safe state and postpones every request that would lead to an unsafe one.

Common mistake

Using “unsafe” and “deadlocked” as synonyms. An unsafe state says only that the guarantee of completion is lost. The banker's algorithm rejects an unsafe state not because it is a deadlock but because a deadlock may occur. Even if the system remains in an unsafe state, the processes may finish without making their maximum requests.

7.6.3A safe-state example

Let there be 10 instances of a single resource type. In the tables, “Has” is the number of instances the process holds right now, and “Max” is the greatest number of instances it will need until it finishes. The remaining need is Max − Has. In avoidance the operating system is in a position to choose the order of requests itself: if a safe sequence exists, it can finish the processes in the order of that sequence.

Example 7.4

A holds 3 instances (Max 9), B holds 2 (Max 4), C holds 2 (Max 7). Of the 10 instances in total, 7 have been handed out and 3 are free. Is the state safe? (Tanenbaum Figure 6-9)

HasMaxA39B24C27Free: 3 HasMaxA39B44C27Free: 1 HasMaxA39B0–C27Free: 5
HasMaxA39B0–C77Free: 0 HasMaxA39B0–C0–Free: 7safe sequence: B, C, A
Figure 7.25: A safe state. (a) Start, free 3. (b) B is given 2, free 1. (c) B finishes, free 5. (d) C is given 5, free 0. (e) C finishes, free 7; A's remaining 6 can be met.
  1. Remaining needs. A: 9 − 3 = 6; B: 4 − 2 = 2; C: 7 − 2 = 5.
  2. B. Its remaining need is 2 ≤ 3. B is given 2 instances; 1 is left free. B reaches its maximum, finishes, and releases 4 instances: free 5.
  3. C. Its remaining need is 5 ≤ 5. C is given 5; 0 is left free. C finishes and releases 7 instances: free 7.
  4. A. Its remaining need is 6 ≤ 7. A finishes too.
  5. Result. ⟨B, C, A⟩ is a safe sequence; the state is safe. Trying all orders shows that there is no other safe sequence: in the first step only B can be satisfied, and after B only C.

7.6.4An unsafe-state example

Start from the same initial state; the difference is a single decision. A asks for one more instance, and the operating system grants it.

Example 7.5

A holds 4 instances (Max 9), B holds 2 (Max 4), C holds 2 (Max 7); free 2. Is the state safe? (Tanenbaum Figure 6-10)

HasMaxA49B24C27Free: 2 HasMaxA49B44C27Free: 0 HasMaxA49B0–C27Free: 4A needs 5, C needs 5; 4 free
Figure 7.26: An unsafe state. (a) A has 4/9, free 2. (b) Only B can be satisfied; B is given 2. (c) B finishes, free 4; A needs 5 and C needs 5, and neither can be guaranteed.
  1. Remaining needs. A: 5; B: 2; C: 5.
  2. B. 2 ≤ 2; B is given 2, finishes, and releases 4 instances: free 4.
  3. A and C. Both have a remaining need of 5, and 5 > 4. Neither can be guaranteed.
  4. Result. There is no safe sequence; the moment A was given the extra instance, the state became unsafe. A's request should have been postponed.

There is no deadlock here yet. If A releases an instance before making its additional request, there may be no trouble. But the operating system assumes the worst case: if everyone makes their maximum request, completion is not guaranteed. Avoidance does not grant the request that loses this guarantee.

7.6.5The banker's algorithm: one resource type

In 1965 Dijkstra described the avoidance algorithm with a banking analogy. A small-town banker extends credit limits to customers. The sum of the limits is more than the cash in the vault, because not all customers ask for their entire limit at the same time. At each request the banker asks, “if I grant this loan, will I in the end be able to meet the limits of all my customers?”

Definition 7.7

The banker's algorithm is an avoidance algorithm that, at every resource request, computes the new state as if the request had been granted, and grants the request if that state is safe and makes the process wait if it is unsafe. The request is re-evaluated later, when resources are released.

The safety check goes like this: find a customer whose remaining need can be met from the money in the vault; this customer is treated as finished and the credit is added back to the vault. The step is repeated until all customers have finished or no one can be satisfied.

Example 7.6

The vault holds 10 units. Four customers have credit limits A 6, B 5, C 4, D 7; the total is 22. After a while A uses 1, B 1, C 2, and D 4 units. Is the state safe? In this state, should a request by B for one more unit be granted? (Tanenbaum Figure 6-11)

HasMaxA06B05C04D07Free: 10Max sums to 22 > 10, yet safe HasMaxA16B15C24D47Free: 2safe sequence: C, D, A, B HasMaxA16B25C24D47Free: 1no need ≤ 1: unsafe
Figure 7.27: The banker's algorithm, one resource type. (a) Start: nobody is using credit, 10 units in the vault. (b) 8 in use, 2 in the vault: safe. (c) If B takes one more unit, 1 is left in the vault: unsafe.
  1. Start. Although the sum of the limits is 22 > 10, as long as nobody is using credit the state is safe; the customers can be finished one after another.
  2. State (b). In use 1 + 1 + 2 + 4 = 8; there are 2 units in the vault. The remaining needs are A 5, B 4, C 2, D 3.
  3. Safe sequence. C's need 2 ≤ 2: C finishes and 4 units come back, 4 in the vault. D's need 3 ≤ 4: D finishes, 8 in the vault. When A (5 ≤ 8) finishes, 9; when B (4 ≤ 9) finishes, 10. ⟨C, D, A, B⟩ is a safe sequence.
  4. B's request. If B takes one more unit, 1 is left in the vault. The remaining needs are A 5, B 3, C 2, D 3; even the smallest is greater than 1. The state is unsafe; the request is refused and B is made to wait.

A state is safe when all the processes, not just one, can finish in some order. The banker's algorithm does not resolve deadlock after the fact; as long as all resource requests go through the algorithm and every process has correctly declared its maximum need in advance, it never lets the system get into deadlock. The price is also clear: in state (c) B is made to wait even though there is actually money in the vault.

Example 7.7

Processes request identical resources of the same type (tape drives) one at a time and release them all when finished. (a) There are 4 processes, and each uses at most 3 drives at once. What is the smallest number of drives that guarantees deadlock never occurs? (b) With 6 processes, at most 4 drives per process, and 18 drives in the system, can deadlock occur? (c) With 18 drives and at most 4 drives per process, what is the largest number of processes that can run safely?

  1. The worst case. Let there be n processes, each requesting at most k drives. In the worst case each process holds k − 1 drives and waits for one more. If there is one more drive, one of the processes completes its need, finishes, and releases its drives. The minimum number needed is n · (k − 1) + 1.
  2. (a) 4 · 2 + 1 = 9 drives. With 8 drives, each of the four processes can hold two drives and wait for a third.
  3. (b) 6 · 3 + 1 = 19 > 18: deadlock can occur. If all 18 drives are distributed three apiece among the six processes, everyone waits for a fourth.
  4. (c) We need 3n + 1 ≤ 18; n ≤ 5.67, so at most 5 processes.

This bound is the number of resources at which hold and wait cannot turn into circular wait, and it corresponds to the single-resource worst case of the banker's algorithm. The values were verified by brute force in Python, trying all distributions.

7.6.6The banker's algorithm: several resource types

The algorithm generalizes directly to several resource types. For n processes and m resource types, using Silberschatz's naming, four data structures are kept:

  • Available[m]: the number of free instances of each type.
  • Max[n][m]: the maximum request each process has declared in advance.
  • Allocation[n][m]: the instances each process currently holds.
  • Need[n][m] = Max − Allocation: the remaining need.
Max [n][m]Allocation [n][m]Need [n][m]−=
Figure 7.28: The remaining-need matrix is found by subtracting the allocation matrix from the maximum-request matrix: Need = Max − Allocation.

The algorithm has two parts. The safety algorithm tells whether a state is safe:

/* safety algorithm */
Work ← Available
Finish[i] ← false  (all i)
while some i has Finish[i] = false
      and Need[i] ≤ Work:
  Work ← Work + Allocation[i]
  Finish[i] ← true
SAFE if Finish[i] for all i

Work is a temporary vector that represents the free pool during the test; Available itself is not modified. Finish[i] records whether process i is considered finished. As long as an unfinished process whose remaining need can be met from Work can be found, that process is considered finished and what it holds is added to Work. If all Finish values are true at the end, the state is safe.

The request algorithm runs when a process asks for Request[i]:

/* Ti requests Request[i] */
if Request[i] > Need[i]:
  error  /* exceeds Max */
if Request[i] > Available:
  Ti waits  /* not available */
/* pretend to allocate: */
Available  -= Request[i]
Allocation[i] += Request[i]
Need[i]    -= Request[i]
if safe: grant the request
else: restore, Ti waits

The first check is an error check: a process cannot ask for more than the maximum it declared. The second check looks at whether the resources are actually free right now; if not, the process has to wait anyway. If both checks pass, the algorithm makes the request as if granted: it updates the three structures and runs the safety algorithm on the new state. If the state is safe, the changes become permanent. If it is unsafe, the three changes are undone and the process is made to wait.

The cost of the safety algorithm is the same as that of the detection algorithm: O(m · n2). The difference is that this test runs at every request.

Common mistake

Adding the Need row of the finished process to Work in the safety algorithm. A finished process releases what it holds, that is, its Allocation row. Need is only the amount required for the process to be able to finish, and it is used in the comparison; what is added to the pool is Allocation.

7.6.7The safety algorithm: an example

Silberschatz's classic example has five threads (T0–T4) and three resource types: 10 instances of type A, 5 of type B, and 7 of type C. The allocations and maximum requests are as follows:

Table 7.8: The initial state of the Silberschatz example.
ThreadAllocation (A B C)Max (A B C)Need (A B C)
T00 1 07 5 37 4 3
T12 0 03 2 21 2 2
T23 0 29 0 26 0 0
T32 1 12 2 20 1 1
T40 0 24 3 34 3 1

The column sums of the allocations are (7 2 5); Available = (10 5 7) − (7 2 5) = (3 3 2). The Need column is computed as Max − Allocation. The safety algorithm starts with Work = (3 3 2) and scans the rows cyclically, beginning at T0 and continuing from where it left off.

Work ← Available
Finish[i] ← false
for i = T0 … T4 (repeatedly):
  if Finish[i] = false and
     Need[i] ≤ Work:
    Work ← Work + Allocation[i]
    Finish[i] ← true
if all Finish[i]: SAFE
Table 7.9: Trace of the safety algorithm.
StepRowNeed ≤ Work?ResultWork afterwards
1T0(7 4 3) ≤ (3 3 2)✗ skip(3 3 2)
2T1(1 2 2) ≤ (3 3 2)✓ + (2 0 0)(5 3 2)
3T2(6 0 0) ≤ (5 3 2)✗ not enough A(5 3 2)
4T3(0 1 1) ≤ (5 3 2)✓ + (2 1 1)(7 4 3)
5T4(4 3 1) ≤ (7 4 3)✓ + (0 0 2)(7 4 5)
6T0 (second pass)(7 4 3) ≤ (7 4 5)✓ + (0 1 0)(7 5 5)
7T2(6 0 0) ≤ (7 5 5)✓ + (3 0 2)(10 5 7)
AllocationABCT0010T1200T2302T3211T4002NeedABCT0743T1122T2600T3011T4431332WorkOrder: — AllocationABCT0010T1200T2302T3211T4002NeedABCT0743T1122T2600T3011T4431743WorkOrder: T1 → T3(0 1 1) ≤ (5 3 2) ✓ Work += (2 1 1)
AllocationABCT0010T1200T2302T3211T4002NeedABCT0743T1122T2600T3011T4431755WorkOrder: T1 → T3 → T4 → T0second round: T0 (7 4 3) ≤ (7 4 5) ✓ AllocationABCT0010T1200T2302T3211T4002NeedABCT0743T1122T2600T3011T44311057WorkOrder: T1 → T3 → T4 → T0 → T2SAFE
Figure 7.29: The safety algorithm. (a) Start: Work = (3 3 2). (b) After T1 and T3 finish, Work = (7 4 3). (c) In the second pass T0 finishes, Work = (7 5 5). (d) All Finish values are true: the state is safe.

All Finish values are true, and at the end Work = (10 5 7), that is, all the resources. The state is safe; the safe sequence found is ⟨T1, T3, T4, T0, T2⟩. The safe sequence is not unique. Trying all orders finds 16 safe sequences for this state; ⟨T1, T3, T4, T2, T0⟩ is one of them. What they all have in common is that the first process is T1 or T3, because with the initial (3 3 2) only these two can be satisfied.

7.6.8Granting a request

In the same state, let T1 ask for Request1 = (1 0 2). The request algorithm decides in three steps.

Example 7.8

T1 requests (1 0 2). Should the request be granted?

AllocationABCT0010T1302T2302T3211T4002NeedABCT0743T1020T2600T3011T4431230Availpretend: Avail (2 3 0), Alloc₁ (3 0 2), Need₁ (0 2 0) AllocationABCT0010T1302T2302T3211T4002NeedABCT0743T1020T2600T3011T44311057WorkOrder: T1 → T3 → T4 → T0 → T2new state safe → request GRANTED
Figure 7.30: T1's request. (a) The pretend state: Available (2 3 0), Allocation1 (3 0 2), Need1 (0 2 0). (b) The safety algorithm finds the sequence ⟨T1, T3, T4, T0, T2⟩: the request is granted.
  1. Need check. (1 0 2) ≤ Need1 = (1 2 2) ✓. T1 does not exceed its declared maximum.
  2. Available check. (1 0 2) ≤ Available = (3 3 2) ✓. The resources are free right now. But this alone is not enough.
  3. The pretend state. Available = (3 3 2) − (1 0 2) = (2 3 0); Allocation1 = (2 0 0) + (1 0 2) = (3 0 2); Need1 = (1 2 2) − (1 0 2) = (0 2 0).
  4. Safety test. Work = (2 3 0). T0 (7 4 3) ✗. T1 (0 2 0) ✓ → Work = (5 3 2). T2 (6 0 0) ✗. T3 (0 1 1) ✓ → (7 4 3). T4 (4 3 1) ✓ → (7 4 5). T0 (7 4 3) ✓ → (7 5 5). T2 (6 0 0) ✓ → (10 5 7).
  5. Decision. The safe sequence ⟨T1, T3, T4, T0, T2⟩ exists; the request is granted and the new state becomes permanent.

The safety test is made on the “pretend” state. Had the state turned out unsafe, all three changes would have been undone and T1 would have been made to wait.

7.6.9Refusing a request

After T1's request has been granted, suppose two new requests arrive. They show two different reasons a process may be made to wait.

Example 7.9

The state is the one after T1's request was granted: Available = (2 3 0). (a) What happens if T4 requests (3 3 0)? (b) What happens if T0 requests (0 2 0)?

AllocationABCT0010T1302T2302T3211T4002NeedABCT0743T1020T2600T3011T4431230AvailT4: (3 3 0) ≤ Avail (2 3 0)? ✗ → wait AllocationABCT0030T1302T2302T3211T4002NeedABCT0723T1020T2600T3011T4431210WorkOrder: —no row fits → UNSAFE → REFUSE
Figure 7.31: Two refusals. (a) For T4's request only 2 instances of type A are free: T4 waits. (b) When T0's request is pretend-granted, Available becomes (2 1 0) and no row can be satisfied: the state is unsafe and the request is refused.
  1. (a) T4. (3 3 0) ≤ Need4 = (4 3 1) ✓. But (3 3 0) ≤ (2 3 0) fails: only 2 instances of type A are free. The resource is not available, so T4 waits. The safety test is never reached.
  2. (b) T0, two checks. (0 2 0) ≤ Need0 = (7 4 3) ✓ and (0 2 0) ≤ (2 3 0) ✓. The resource is actually free.
  3. The pretend state. Available = (2 1 0); Allocation0 = (0 3 0); Need0 = (7 2 3).
  4. Safety test. Work = (2 1 0). T0 (7 2 3): not enough A. T1 (0 2 0): not enough B. T2 (6 0 0): not enough A. T3 (0 1 1): not enough C. T4 (4 3 1): not enough A. No row can be satisfied.
  5. Decision. The state is unsafe. The changes are undone and T0 is made to wait, even though the resource is free.

In the first case the resource is not available; in the second it is, but granting would make the state unsafe. The price of avoidance is the second case: requests are sometimes postponed while resources sit idle, and resource utilization drops.

7.6.10Code trace: the banker's request algorithm

To trace the request and safety algorithms together, return to the initial state: Available = (3 3 2). This time T3 requests Request = (0 1 1). The code gives the two algorithms together:

/* Ti requests Request */
if Request > Need[i]: error /* exceeds Max */
if Request > Available: Ti waits
Available -= Request  /* pretend */
Allocation[i] += Request
Need[i] -= Request
if safe(): GRANT the request
else: restore, Ti waits
safe():
  Work ← Available; Finish ← false
  for i = T0 … T4 (repeatedly):
    if !Finish[i] and Need[i] ≤ Work:
      Work ← Work + Allocation[i]
      Finish[i] ← true
  return all Finish[i]
Table 7.10: Trace of T3's request for (0 1 1).
StepLineEvaluationValues changed
1Request > Need[3]?(0 1 1) ≤ (0 1 1): maximum not exceeded—
2Request > Available?(0 1 1) ≤ (3 3 2): resources available—
3pretendthe three structures are updatedAvailable (3 2 1), Allocation[3] (2 2 2), Need[3] (0 0 0)
4safe()Work ← (3 2 1); T0 (7 4 3), T1 (1 2 2), T2 (6 0 0) cannot finishWork (3 2 1)
5T3(0 0 0) ≤ (3 2 1) ✓Work (5 4 3), Finish[3]
6T4(4 3 1) ≤ (5 4 3) ✓Work (5 4 5), Finish[4]
7T0, T1 (second pass)not enough A for T0; T1: (1 2 2) ≤ (5 4 5) ✓Work (7 4 5), Finish[1]
8T2(6 0 0) ≤ (7 4 5) ✓Work (10 4 7), Finish[2]
9T0 (third pass)(7 4 3) ≤ (10 4 7) ✓Work (10 5 7), Finish[0]
10resultall Finish true: safesequence ⟨T3, T4, T1, T2, T0⟩; the request is granted
AllocationNeedFinishT00 1 07 4 3—T12 0 01 2 2—T23 0 26 0 0—T32 2 20 0 0—T40 0 24 3 1— AllocationNeedFinishT00 1 07 4 3—T12 0 01 2 2—T23 0 26 0 0—T32 2 20 0 0✓T40 0 24 3 1✓Work (5 4 5)
AllocationNeedFinishT00 1 07 4 3—T12 0 01 2 2✓T23 0 26 0 0✓T32 2 20 0 0✓T40 0 24 3 1✓Work (10 4 7) AllocationNeedFinishT00 1 07 4 3✓T12 0 01 2 2✓T23 0 26 0 0✓T32 2 20 0 0✓T40 0 24 3 1✓Work (10 5 7)
Figure 7.32: Trace of T3's request. (a) The pretend state: Allocation[3] = (2 2 2), Need[3] = (0 0 0). (b) T3 and T4 have finished, Work = (5 4 5). (c) T1 and T2 have finished too, Work = (10 4 7). (d) T0 finishes as well: all Finish values are true.

The notable point in the trace is that T1 cannot finish in the first pass. In the initial state T1 could finish immediately. But because T3 was given one B and one C, Work = (3 2 1), and T1's need for C is 2 > 1. Since T3's remaining need drops to (0 0 0), T3 finishes at once and returns the (2 2 2) it holds; after that the chain builds up. All the values were recomputed in Python with the request and safety algorithms themselves.

7.6.11A second example

Tanenbaum's multi-resource example has five processes (A–E) and four resource types: tape drive (Tp), plotter (Pl), printer (Pr), and CD. The existing resources are E = (6 3 4 2), and the total of assigned resources is P = (5 3 2 2). The available resources are A = E − P = (1 0 2 0).

AssignedTpPlPrCDA3011B0100C1110D1101E0000Still neededTpPlPrCDA1100B0112C3100D0010E2110E = (6 3 4 2)P = (5 3 2 2)A = (1 0 2 0)E = existing, P = total assigned, A = E − P (available)
AssignedTpPlPrCDA3011B0110C1110D1101E0010Still neededTpPlPrCDA1100B0102C3100D0010E2100E = (6 3 4 2)P = (5 3 4 2)A = (1 0 0 0)then E requests the last printer → A = (1 0 0 0), no one can finish → DEFER
Figure 7.33: The banker's algorithm with several resources (Tanenbaum Figure 6-12). Top: the initial state, with the assigned resources, the resources still needed, and the vectors E, P, A. Bottom: the state after B and E are each given a printer: with A = (1 0 0 0) no row can be satisfied.
Example 7.10

The resources still needed are A (1 1 0 0), B (0 1 1 2), C (3 1 0 0), D (0 0 1 0), E (2 1 1 0). Is the state safe? If B requests a printer, should it be granted? What happens if E then requests the last printer?

  1. Safety. D's need (0 0 1 0) ≤ (1 0 2 0). D finishes and (1 1 0 1) comes back: A = (2 1 2 1). Then E (2 1 1 0) ≤ (2 1 2 1) finishes; since E holds nothing, A does not change. A finishes, A = (5 1 3 2); B finishes, (5 2 3 2); C finishes, (6 3 4 2). ⟨D, E, A, B, C⟩ is a safe sequence.
  2. B's printer request. Pretend-granted, A = (1 0 1 0) and P = (5 3 3 2); B's need drops to (0 1 0 2). D can still finish ((0 0 1 0) ≤ (1 0 1 0)) and the same sequence is kept. The request is granted.
  3. E's printer request. Pretend-granted, A = (1 0 0 0) and P = (5 3 4 2). The plotter needs of A and B, the tape and plotter needs of C, the printer need of D, and the plotter need of E cannot be met. No row is ≤ A: the state is unsafe and the request is postponed.

The steps “look for a row that is ≤ A” are the safety test here. The same logic is used with the request matrix in the detection algorithm and with the remaining-need matrix in avoidance. The code of the two algorithms is almost identical; only the meaning of the row being compared changes.

7.6.12The banker's algorithm in practice

The banker's algorithm is an elegant idea, but it rests on four assumptions:

  • Every process declares its maximum need in advance.
  • The number of processes is fixed.
  • The number of resources does not change; for example, a device does not fail.
  • Processes release resources in a finite time.

These assumptions do not hold in general-purpose operating systems. How much memory or how many file locks a word processor will request is not known in advance; processes are born and die all the time; a disk can fail. That is why the algorithm is almost never used in real operating systems. A similar “admission control” idea, however, is common. In real-time scheduling, one checks whether a new task would break the timing guarantees of the other tasks. In cloud systems quotas are set, and connection pools have upper limits.

Avoidance is usually more expensive than detection and recovery because of the test at every request, which costs O(m · n2), and because of needless postponements. Its advantage is that it needs no recovery. The algorithm does not run continuously in the background: the test is made only when a request arrives and, for waiting requests, when a resource is released.

7.7Deadlock prevention

Avoidance requires knowing the future requests of the processes, and in practice that information is not available. Prevention takes a more radical route: since the four conditions are jointly necessary, removing one of them from the system altogether makes deadlock impossible. The decision is made at design time, not at run time.

7.7.1Attacking the conditions

Table 7.11 summarizes the method used against each condition and its price.

Table 7.11: Ways of attacking the four conditions.
ConditionAttackPrice
Mutual exclusionMake the resource shareable: spooling, read-only sharing, lock-free structuresMost resources are inherently unshareable (the mutex itself!)
Hold and waitRequest all resources at once up front, or release what you hold before a new requestLow utilization, starvation; needs must be known in advance
No preemptionTake back the resources of a process that is about to wait; back off with tryLock; virtualizeOnly for resources whose state can be saved; risk of livelock
Circular waitGive the resources a total order and request only in increasing order (lock ordering)Following the order takes programmer discipline

Two misunderstandings are common. Removing mutual exclusion does not mean “only one process may request the resource at a time”; that is mutual exclusion itself. Removing the “no preemption” condition does not mean “let the process keep its resources until it finishes”; on the contrary, it means that resources can be taken back from their owner.

7.7.2Attacking mutual exclusion

If a resource can be given to several processes at the same time, nobody waits for it and it cannot take part in a deadlock. The printer is the classic example.

Definition 7.8

Spooling is queuing the jobs destined for a slow device on disk and sending them to the device in turn. Processes write their output to a spool directory; only a single background process (a daemon) uses the device.

P1P2P3spooldirectorylpdprintersole ownerOnly the daemon holds the printer:user processes never wait for it
Figure 7.34: Printer spooling. P1, P2, and P3 write their output to the spool directory; only the lpd daemon holds the printer. User processes never wait for the printer.

From the processes' point of view the printer is now shareable: everyone can leave a job at the same time, and a single process uses the real device. Contention for the printer disappears. There are other examples. Read-only files and the code pages of programs are shared at the same time. Reader locks do not exclude each other; only a writer lock excludes. Lock-free data structures advance with the compare-and-swap (CAS) instruction; since there is no lock, there is no deadlock, but starvation is still possible.

The method has a limit: the spool disk is also a resource. In Tanenbaum's example many processes have written half of their output to the disk and the disk has filled up. Since no output is complete, the daemon does not start printing, and the processes wait for space: deadlock again. The general principle is this: a resource is assigned only when it is truly needed, and the number of processes that may request it is kept to a minimum.

7.7.3Attacking hold and wait

If no process waits for another resource while holding one, no ring can be built. There are two protocols for achieving this:

  1. Protocol 1. The process obtains all the resources it will need in a single request before it starts running: all or nothing.
  2. Protocol 2. A process may make a request only when it holds no resources. Before asking for a new resource it releases everything it holds.

In Silberschatz's example a process copies data from a DVD to disk, sorts the file on disk, and prints the result on the printer. In Protocol 1 the process acquires the DVD drive, the disk file, and the printer at the start. Although the printer is needed only at the very end, it is held from the beginning and nobody else can use it. In Protocol 2 the process first takes the DVD and the disk, copies, and releases both; then it takes the disk and the printer. Utilization improves, but other problems arise: by the time the process asks for the disk the second time, someone else may have modified the file.

1) Request all up frontDVDDiskPrinter2) Release, then requestDVDDiskPrinterin useheld idle
Figure 7.35: Timelines of the two protocols. In Protocol 1 the printer is held from the very start and most of that time is wasted. In Protocol 2 the resources are held only while they are used (Silberschatz §8.5.2).

The two protocols share some problems. Resource utilization drops, because resources are held even when they are not needed. A process that wants many popular resources may never get started, because they are never all free at the same time; this too is starvation. In addition, the needs are often not known in advance. In practice this idea lives on in two places: “all or nothing” acquisition with pthread_mutex_trylock, and conservative two-phase locking in databases that takes all locks up front.

7.7.4Attacking no preemption

If resources can be taken back by force, the ring of waiting can be broken. Silberschatz gives the following preemption protocol: if a process holding resources makes a request that cannot be satisfied at once, all the resources it holds are implicitly released. The process is restarted when it can obtain its old resources and the new one it asked for together.

This protocol suits only resources whose state can be saved and restored: CPU registers, memory, database transactions. A print job interrupted halfway or a data structure protected by a mutex cannot be taken back this way. Some resources are made preemptable by virtualizing them: the printer is spooled, memory is paged.

For a mutex, a workable approach is the timed attempt. A thread that cannot get the second lock within a certain time releases the lock it holds, of its own accord, and tries again after a random time. The resource is not taken by force, but its owner gives it up voluntarily; the result is the same, and the ring is broken.

7.7.5Code trace: backing off with tryLock

In Java, ReentrantLock.tryLock(time, unit) waits for the lock for at most the given time; it returns true if it gets the lock and false if it does not. The method below transfers money from one account to another. Each account has its own lock.

boolean tryXfer(Account a, Account b, int m)
        throws InterruptedException {
  if (!a.lock.tryLock(50, MILLISECONDS))
    return false;
  try {
    if (!b.lock.tryLock(50, MILLISECONDS))
      return false;  /* a released too */
    try { a.balance -= m; b.balance += m;
          return true; }
    finally { b.lock.unlock(); }
  } finally { a.lock.unlock(); }
}
/* caller: while (!tryXfer(x, y, 1))
              Thread.sleep(random); */

The method first waits at most 50 ms for the lock of the source account (a). If it cannot get it, it returns false at once. If it gets it, it also waits 50 ms for the lock of the destination account (b). If the second lock cannot be obtained, return false executes; but the outer finally block releases a's lock before the return. So it is the finally that makes the comment “a released too” come true. If both locks are obtained, the transfer is made and the locks are released in reverse order. The caller sleeps for random times and retries until the method succeeds.

Let two threads transfer in opposite directions: T1 moves 1 unit from x to y, and T2 moves 1 unit from y to x. Both accounts start with 1000 units. Table 7.12 traces one unlucky timing.

Table 7.12: Trace of backing off with tryLock.
t (ms)T1T2x locky lockx / y balance
0readyreadyfreefree1000 / 1000
0gets x at oncereadyT1free1000 / 1000
1holds xgets yT1T21000 / 1000
2tries y (≤ 50 ms)tries x (≤ 50 ms)T1T21000 / 1000
52timed out: falsetries xT1T21000 / 1000
52finally: releases xtries xfreeT21000 / 1000
52sleeps randomlygets xT2T21000 / 1000
52sleepingtransfersT2T21001 / 999
53sleepingreleases x, then y; truefreefree1001 / 999
70retries, gets both locks, and transfersdoneT1T11000 / 1000
trying ytrying xT1T2xyx.balance = 1000 · y.balance = 1000t = 2 ms released xtrying xT1T2xyx.balance = 1000 · y.balance = 1000t = 52 ms
sleepingtransferringT1T2xyx.balance = 1001 · y.balance = 999t = 52 ms both locksdoneT1T2xyx.balance = 1000 · y.balance = 1000t = 70 ms
Figure 7.36: Backing off with tryLock. (a) Each waits at most 50 ms for the second lock: circular wait exists, but it is timed. (b) T1's time runs out and finally releases x. (c) T2 gets x and transfers. (d) After sleeping a random time, T1 retries; the total is again 2000.

At step 2 a circular wait really does form, but it is not unbounded. At the 52nd millisecond T1 gives up and releases x; the no-preemption condition has been broken voluntarily. With a plain lock(), the deadlock would have become certain at t = 2 ms. The program was run with JDK 21 using 2 threads and 1000 opposite-direction transfers each: the result is x=1000 y=1000 total=2000, and the program finished every time.

The random wait is important. If two threads always wait the same time and retry at the same moment, the same collision can happen again and again. The processes are not blocked, but none makes progress; this situation is called livelock.

7.7.6Attacking circular wait

The prevention method used most in practice is to break circular wait. Each resource type is given a number, and processes are allowed to request resources only in increasing numerical order.

Table 7.13: An example of resource numbering (Tanenbaum).
#Resource
1Imagesetter
2Printer
3Plotter
4Tape drive
5Blu-ray drive

A process that needs the printer and the tape drive asks first for 2 and then for 4. After it holds the tape drive it cannot ask for the printer.

Theorem 7.3 (Resource ordering)

If every process requests resources only with numbers greater than those it already holds, circular wait cannot occur.

First consider the case of two processes. If A holds resource number i and requests j, the rule says i < j. If B holds j and requests i, we would need j < i. Both cannot be true; this edge never arises. In the general case, suppose there is a cycle, and call the resource with the greatest number on the cycle Rk. The process holding Rk waits for the next resource on the cycle. That resource's number is less than k, because k is the greatest. But by the rule a process may not request a resource numbered lower than what it holds. A contradiction; there is no cycle.

ABijA: holds i, requests j → i < j ABijB: holds j, requests i → j < i ?i < j and j < i can't both hold: contradiction
Figure 7.37: Numbering breaks the cycle (Tanenbaum Figure 6-13). (a) If A holds i and requests j, then i < j. (b) B holding j and requesting i would require j < i: a contradiction, so this edge cannot arise.

There is also a variant of the rule: if a process is going to request Rj, it first releases all the Ri (i ≥ j) that it holds. The hardest part of this method is finding a suitable ordering that all programs will follow. If a process in the natural flow of its work uses the tape drive before the printer, then to obey the rule it has to acquire the printer earlier than it needs it.

Example 7.11

The resources are numbered as in Table 7.13. Processes make the following sequences of requests without releasing anything. Which follows the rule? (a) Tape → Printer → Blu-ray, (b) Plotter → Imagesetter → Tape, (c) Blu-ray → Plotter → Tape, (d) Printer → Tape → Blu-ray.

  1. (a) 4 → 2 → 5: the printer (2) is requested while the tape drive (4) is held; this violates the rule.
  2. (b) 3 → 1 → 4: the imagesetter (1) is requested while the plotter (3) is held; it violates the rule.
  3. (c) 5 → 3 → 4: the plotter (3) is requested while the Blu-ray drive (5) is held; it violates the rule.
  4. (d) 2 → 4 → 5: strictly increasing; the only sequence that follows the rule.

7.7.7Lock ordering in practice

The software counterpart of resource numbering is lock ordering. Return to the example of transfers in opposite directions. T1 transfers from x to y, and T2 from y to x. The “natural” order, locking the source account first and then the destination account, is reversed between the two threads and is open to deadlock. The solution is to take the locks according to the accounts' ID numbers; this order is common to all threads.

void transfer(Account a, Account b, int m) {
  Account first = a.id < b.id ? a : b;
  Account second = a.id < b.id ? b : a;
  first.lock.lock();
  try {
    second.lock.lock();
    try { a.balance -= m; b.balance += m; }
    finally { second.lock.unlock(); }
  } finally { first.lock.unlock(); }
}
/* T1: transfer(x, y, 1)   x.id = 1
   T2: transfer(y, x, 1)   y.id = 2 */

first is always the account with the smaller number and second the one with the larger number. Whichever direction the transfer goes, the locks are taken in the same order. The transfer line is written in terms of a and b, so the direction is preserved. Figure 7.38 shows the trace of the two threads.

T1T2xyid 1id 2 T1T2xyid 1id 2
T1T2xyid 1id 2 T1T2xyid 1id 2
Figure 7.38: Lock ordering. (a) For T1, first = x (1 < 2); it takes x. (b) For T2, a = y but first is still x; T2 waits for x and holds no lock. (c) T1 takes y too and transfers. (d) T1 releases the locks; T2 takes x and then y. No cycle can form.
  1. T1 calls transfer(x, y, 1). Since x.id = 1 < y.id = 2, first = x. T1 takes x.
  2. T2 calls transfer(y, x, 1). Here a = y, but first is still x (id 1). T2 waits for x. What matters is that T2 holds no lock while it waits.
  3. T1 takes y as well; nobody holds y. It makes the transfer.
  4. T1 releases the locks. T2 takes x, then y, and makes its own transfer.

The program was run with JDK 21, each thread making 100,000 opposite-direction transfers; the result is x=1000 y=1000 and there was no deadlock. The Linux kernel uses the same method: it takes two locks of the same type in order of their memory addresses. The double_rq_lock function, which locks two of the scheduler's run queues together, is an example. The lock order in the kernel is documented and checked with lockdep.

Common mistake

Applying the lock order in only one function. Ordering works only if it is applied in every place where the locks are acquired. If another function takes the same two locks in the opposite order, a cycle can still form. That is why in large projects the lock order is documented and checked with tools.

7.8Other issues

Deadlock is not the only problem of concurrent programs. The locking protocols of databases, processes that communicate by messages, processes that keep trying but make no progress, and processes whose turn never comes give rise to similar but different problems. This section tells them apart from deadlock.

7.8.1Two-phase locking

Definition 7.9

Two-phase locking (2PL) is a protocol for database transactions. In the growing phase the transaction only acquires locks; in the shrinking phase it only releases them. After the first release no new lock may be acquired.

timelocks heldlock pointgrowingshrinking
Figure 7.39: Two-phase locking. The number of locks held rises in the growing phase and falls in the shrinking phase after the lock point.

The purpose of 2PL is not to prevent deadlock but serializability: the result of concurrently running transactions is as if the transactions had run one after another. Plain 2PL can deadlock. T1 locks record a and T2 locks record b; then T1 requests b and T2 requests a. Both transactions are in the growing phase and wait for each other.

Tanenbaum describes a variant: in the first phase the transaction tries to lock all the records. If another transaction has locked one of them, it releases everything it holds and starts over. This variant removes hold and wait, because the transaction never waits while holding a lock. In strict 2PL, which is common in today's databases, the locks are released at the end of the transaction, at commit or abort. This variant can deadlock too; the database management system detects the deadlock with a wait-for graph and rolls back one of the transactions.

7.8.2Communication deadlocks

All the deadlocks so far have been resource deadlocks. In processes that communicate by messages, deadlock can occur without any resource. A sends a request to B and waits for the reply. If the request is lost in the network, A waits forever for the reply and B waits forever for the request. Since each process waits only for an event the other could trigger, this is a deadlock; but no resource is being held.

In this kind of communication deadlock, resource ordering and avoidance do not help, because there is no resource to order or to compute with. The solution is the timeout: if the sender gets no reply within a certain time, it sends the message again. This creates a new problem: if the original message was not lost but only delayed, the receiver gets the same request twice. To tell duplicate messages apart, the protocol needs sequence numbers.

In network hardware, buffers are real resources. Figure 7.40 shows a network of four routers connected in a ring.

ABCD ABCDevery buffer full;packets bound for the next ABCDevery buffer full;packets bound for the nextno one can send: resource deadlock
Figure 7.40: Resource deadlock in routers (Tanenbaum §6.7.2). (a) Four routers are connected in a ring; each has limited buffer memory. (b) Under heavy traffic all the buffers fill up with packets bound for the next router clockwise. (c) Nobody can send: A waits for B's free buffer, B for C's, C for D's, and D for A's.

This time the deadlock is a resource deadlock, and the circular wait is plainly visible. The solutions also rest on prevention ideas: dropping packets on timeout (preemption), using virtual channels, and preventing the buffers from filling in the first place with credit-based flow control.

7.8.3Livelock

Consider two people who meet in a narrow corridor. Both politely step to the right at the same moment, then both step to the left at the same moment. Nobody bumps into the wall, both keep moving, but neither gets past.

Definition 7.10

Livelock is a situation in which the processes are not blocked and keep changing their state, but none of them makes progress. In a deadlock the processes sleep; in a livelock they run but do no useful work.

In Tanenbaum's example the processes acquire resources by busy waiting. If enter_region cannot get the lock, it keeps spinning in a loop:

void process_A(void) {
  enter_region(&resource_1);
  enter_region(&resource_2);
  use_both_resources();
  leave_region(&resource_2);
  leave_region(&resource_1);
}  /* B: resource_2 first, then 1 */

If B takes the resources in reverse order, A gets resource_1 and B gets resource_2. Then, since neither can get the other's, both spin forever. The processes are not blocked and they burn CPU time; yet they make no progress. A more typical livelock shows up in two threads that back off with tryLock:

ABtimeget r1r2 ✗get r2r1 ✗both releaseget r1r2 ✗get r2r1 ✗both releaseget r1r2 ✗get r2r1 ✗both releasestate changes, work doesn't advance
ABtimer1, r2 ✓waitr2, r1 ✓random backoff breaks the rhythm
Figure 7.41: Livelock. Top: A gets r1 and B gets r2; each tries the other's, fails, and releases at the same moment. The same rhythm repeats: the state changes, the work does not advance. Bottom: random backoff breaks the rhythm and both processes get their resources.
  1. A gets r1 and B gets r2. A tries r2 and B tries r1; both attempts fail.
  2. Both behave politely: each releases what it holds and retries after the same delay.
  3. The same thing repeats. The processes are not blocked, they use CPU time, and their state keeps changing; but neither makes progress.

The remedy is to break the rhythm. A random wait time that grows with each failure (exponential backoff) makes it improbable that the two processes retry at the same moment. Giving priorities or sequence numbers and using lock ordering also prevent livelock. The exponential backoff in Ethernet's CSMA/CD protocol rests on the same idea: two colliding stations wait random times.

7.8.4Starvation

Definition 7.11

Starvation is the indefinite waiting of a process whose turn never comes even though the resource is available. The other processes progress; the system is not deadlocked.

Starvation is a consequence of the resource-allocation policy. For example, giving the printer to the smallest file every time reduces the average waiting time. But if new small jobs keep arriving, a 100 MB file never gets its turn.

printernew small jobs keep arrivinglarge job100 MBwaiting… waiting…remedy: FIFO or aging
Figure 7.42: Starvation. Under the shortest-job-first policy, a steady stream of small jobs makes the large job wait indefinitely. The remedy is FIFO or aging.

There are other examples of starvation: a low-priority job under strict priority scheduling, a writer in a readers-preference readers–writers lock, a process chosen as the victim every time during recovery. The remedy is either a first-in, first-out (FIFO) policy or aging, which raises a process's priority as it waits. Table 7.14 compares the three problems.

Table 7.14: Comparison of deadlock, livelock, and starvation.
DeadlockLivelockStarvation
Process stateblockedrunningready or blocked
Who is affected?everyone on the cyclethe interacting groupone or a few processes
Does the system progress?those off the cycle dothe group does notyes, only the starved one does not
Typical remedyordering, detection, avoidancerandom backoffFIFO, aging

7.8.5Bugs that are not deadlocks: atomicity and ordering

When people think of concurrency bugs, deadlock comes to mind first, but the most common bug is not deadlock. In 2008 Lu and colleagues studied 105 concurrency bugs in MySQL, Apache, Mozilla, and OpenOffice. Of these, 74 are non-deadlock bugs, and almost all of them fit two patterns.

Atomicity violation. Another thread gets in between two accesses that were supposed to be atomic together.

/* T1 */
if (sess->name != NULL)
    puts(sess->name);  /* NULL now? */
/* T2 */
sess->name = NULL;

T1 first checks that sess->name is not NULL, then prints it. If T2 sets the field to NULL between the two lines, puts is called with a null pointer and the program crashes. The remedy is to put the check, the use, and T2's write under the same mutex.

Order violation. It is assumed that “A happens before B,” but nothing enforces that order.

/* T1: init() */
worker = thread_create(body);
/* T2: body(), the new thread */
s = worker->state;  /* worker set yet? */

T1 creates the new thread and assigns its handle to the variable worker. The new thread (T2) accesses worker->state on its first line; the programmer has assumed that the assignment will be made first. But the new thread can start running before thread_create returns and the assignment is made. Then worker has not been assigned yet. The remedy is a ready flag and a condition variable: T2 waits with while (!ready) wait, and T1 sets ready = 1 after the assignment and signals. A semaphore that starts at zero does the same job.

Common mistake

Thinking “if every access is locked, the code is correct.” Even if the check and the use are each locked separately, an atomicity violation persists if the lock is released in between. Data-race tools such as ThreadSanitizer may not see this case, because each access is protected on its own. The unit that must be atomic is not the individual accesses but the check and the use as a whole.

7.9Deadlock in practice

General-purpose operating systems do not concern themselves with the deadlocks of user programs; the responsibility lies with the programmer. This section explains, with Java and Linux examples, how deadlock shows up in everyday code, how encapsulation hides it, and with what tools it is found. The Java programs in this section were compiled and run with JDK 21.

7.9.1Deadlock in Java

In Java every object has a monitor. A synchronized (a) { … } block acquires the monitor of a and releases it when the block ends. A monitor can belong to only one thread at a time; this is mutual exclusion. The following two threads acquire two monitors in opposite orders:

Object a = new Object(), b = new Object();

Thread t1 = new Thread(() -> {
  synchronized (a) {
    nap(10);   /* widen the window */
    synchronized (b) { work(); }
  }
}, "T1");
Thread t2 = new Thread(() -> {
  synchronized (b) {
    nap(10);
    synchronized (a) { work(); }
  }
}, "T2");
t1.start(); t2.start();

nap(10) is a helper method that calls Thread.sleep(10); it widens the deadlock window after the first lock has been acquired. work() stands for the work done under both locks. The states of Java threads also help in tracking down a deadlock: RUNNABLE means ready to run or running, TIMED_WAITING means in a timed sleep, and BLOCKED means waiting for a monitor.

Table 7.15: Trace of synchronized blocks in reverse order.
StepEventOwner of aOwner of bT1T2
1t1.start(); t2.start();——RUNNABLERUNNABLE
2T1 enters a's monitor and sleepsT1—TIMED_WAITINGRUNNABLE
3T2 enters b's monitor and sleepsT1T2TIMED_WAITINGTIMED_WAITING
4T1 wakes and requests b: b is held by T2T1T2BLOCKEDTIMED_WAITING
5T2 wakes and requests a: a is held by T1T1T2BLOCKEDBLOCKED
T1T2ab T1T2abBLOCKED: a cycle
Figure 7.43: Deadlock in Java. (a) T1 holds a and T2 holds b. (b) Each requests the other's monitor and becomes BLOCKED: a cycle.

JVM monitors are nonpreemptable; there is no way to interrupt a waiting synchronized block, to put a timeout on it, or to take the lock back. The program never finishes. nap(10) makes the deadlock very likely but does not guarantee it: if one thread acquires the second lock before the other has even started, the program finishes normally. When these notes were checked, the program was run with JDK 21, and in five runs out of five the two threads stayed BLOCKED. A version that sleeps 50 ms instead of 10 ms likewise printed nothing until it was stopped by an eight-second timeout. A version that makes the threads wait with a CountDownLatch until both first locks have been acquired deadlocks on every run, because it leaves no room for timing.

7.9.2Encapsulation hides lock order

Reverse-ordered locks are not always plainly visible in the code. Collections.synchronizedList wraps a list and protects each of its methods with the list's own lock. The call a.addAll(b) first acquires the lock of a internally. Then, to copy the argument's elements, it calls b.toArray(), which acquires the lock of b.

var a = Collections.synchronizedList(
          new ArrayList<Integer>());
var b = Collections.synchronizedList(
          new ArrayList<Integer>());
/* inside a.addAll(b):               */
/* synchronized (a) { b.toArray() }  */
/*   → synchronized (b) { ... }      */
new Thread(() -> a.addAll(b)).start();
new Thread(() -> b.addAll(a)).start();

/* Fix: take the copy outside the lock */
Integer[] k = b.toArray(new Integer[0]);
a.addAll(Arrays.asList(k));
T1T2alockblockholds T1T2alockblockholdsholds T1T2alockblockholdsholdswantswantscycle: deadlock
Figure 7.44: A hidden lock order. (a) T1: a.addAll(b) acquires a's lock first. (b) At the same time T2: b.addAll(a) acquires b's lock first. (c) Internally b.toArray() and a.toArray() are called; each asks for the other's lock.

If two threads call a.addAll(b) and b.addAll(a) at the same time, an acquisition in reverse order arises on its own: one locks in the order a → b, the other in the order b → a. The person who wrote the code sees no lock at all. The fix is to take the copy outside the lock: b.toArray() is done first in a separate call and releases its own lock; then a.addAll acquires only the lock of a. At no moment are two locks held together.

Table 7.16: Cross addAll trials (2 threads × 200,000 rounds; number of deadlocked runs out of 10; the result can vary from run to run, e.g. 9/10).
Cross callJDK 8JDK 21
Vector: a.addAll(b) ‖ b.addAll(a)10/100/10
synchronizedList: same10/1010/10
Fixed version0/100/10

The interesting row in the table is Vector. In JDK 8, Vector.addAll calls the argument's toArray() while holding its own lock, and deadlocks. In JDK 21 it calls the argument's toArray() before taking its own lock, so it does not deadlock. The same source code behaves differently because an internal detail of the library changed. The rule is: do not call a foreign method, that is, one whose internal locking is unknown, while holding a lock. When these notes were checked, the same experiment was repeated: in JDK 8, Vector and synchronizedList deadlocked in 10 of 10 trials. In JDK 21, synchronizedList deadlocked in 9 of 10 trials and Vector never deadlocked. The fixed code never deadlocked in either version. Because deadlock depends on chance, the difference between 9 and 10 is expected variation.

7.9.3Finding a deadlock: jstack

A deadlocked Java program gives no error message; it simply stops. The jstack tool that comes with the JDK prints the stacks of all threads in a running JVM and, if there is a deadlock, reports it separately at the end of the output:

$ jstack <pid>
Found one Java-level deadlock:
=============================
"T1":
  waiting to lock monitor 0x… (object 0x…, a java.lang.Object),
  which is held by "T2"
"T2":
  waiting to lock monitor 0x… (object 0x…, a java.lang.Object),
  which is held by "T1"

Java stack information for the threads listed above:
"T1":
        at Hang.run(Hang.java:7)
        - waiting to lock <0x…d0> (a java.lang.Object)
        - locked <0x…c0> (a java.lang.Object)
…
Found 1 deadlock.

The report says who is waiting for which monitor and who holds that monitor: T1 waits for the monitor held by T2, and T2 for the one held by T1. The stack information also shows on which line of the code the deadlock arises. When these notes were checked, jstack was run while the deadlocked program was running on JDK 21, and the report came out in the same form: “Found one Java-level deadlock,” the “waiting to lock” and “which is held by” lines for the two threads, and at the end “Found 1 deadlock.” The same report can be obtained with jcmd <pid> Thread.print; in graphical tools such as JConsole and VisualVM, the “Detect Deadlock” button does the same job.

A program can also find its own deadlock. The ThreadMXBean interface exposes the JVM's thread information:

ThreadMXBean mx =
    ManagementFactory.getThreadMXBean();
long[] ids = mx.findDeadlockedThreads();
if (ids != null)
  for (ThreadInfo ti : mx.getThreadInfo(ids))
    System.out.println(ti.getThreadName()
      + " waits, lock owner "
      + ti.getLockOwnerName());

findDeadlockedThreads() returns the IDs of the deadlocked threads; if there is no deadlock it returns null. On the deadlocked program this code prints the following:

T1 waits, lock owner T2
T2 waits, lock owner T1
T1T2waiting (…d0)waiting (…c0)
Figure 7.45: The wait-for graph the JVM builds: T1 waits for the object held by T2 (…d0), and T2 for the object held by T1 (…c0).

The JVM builds a wait-for graph from monitor and ReentrantLock ownership and searches it for cycles; that is, it runs the detection algorithm for single-instance resources. But it only detects; it does not recover. The JVM cannot kill a thread and hand its monitor to someone else, because the protected data might be left inconsistent. The deadlocked process has to be restarted.

7.9.4lockdep and other tools

Every environment has its own tools for deadlock. Table 7.17 lists the main ones.

Table 7.17: Deadlock-finding tools.
EnvironmentTool or behavior
Linux kernellockdep (CONFIG_PROVE_LOCKING): lock-order validator; hung-task detector
C/C++ThreadSanitizer: lock-order-inversion warning; Valgrind Helgrind
Javajstack, jcmd, ThreadMXBean
Goruntime: fatal error: all goroutines are asleep - deadlock!
DatabasePostgreSQL, InnoDB: wait-for graph and rollback of a victim transaction

lockdep in the Linux kernel rests on a different idea. It ties every lock to a class; all lock instances of the same kind belong to the same class. When a task holding a lock of class A acquires a lock of class B, an edge “A → B” is added to the graph. If on another code path A is acquired while B is held, a cycle forms in the graph and lockdep issues a “possible circular locking dependency” warning.

mmap_locki_rwsempath 1: A then B mmap_locki_rwsempath 1: A then Bpath 2: B then A (another time)possible circular locking dependency
Figure 7.46: lockdep. (a) On one path, i_rwsem is acquired while mmap_lock is held: the edge A → B is recorded. (b) At another time, on another path, the reverse order is seen: the cycle is reported without a deadlock ever having occurred.

The two code paths may never have run at the same time; lockdep warns all the same. Tools fall into two groups in this respect. lockdep and ThreadSanitizer find a possible deadlock, that is, a lock-order violation, even if no deadlock has ever occurred. jstack and the Go runtime report a deadlock that has occurred. The first group are tools of the prevention strategy and the second of the detection strategy.

7.10Summary

  • Deadlock is the situation in which every process in a set waits for an event that only another process in the set can trigger. Deadlocks concern nonpreemptable resources; preemptable resources such as the CPU and memory can be reallocated.
  • A process requests, uses, and releases a resource. Acquiring two resources in reverse order turns a program that never deadlocks into one that deadlocks now and then.
  • The four conditions are jointly necessary: mutual exclusion, hold and wait, no preemption, and circular wait. The first three are policy; the fourth is the current state.
  • If the resource-allocation graph has no cycle, there is no deadlock. With single-instance resources, cycle ⇔ deadlock; with multiple-instance resources a cycle is necessary but not sufficient. In the single-instance case the wait-for graph is used.
  • There are four strategies: ignoring (the ostrich), detection and recovery, avoidance, and prevention. General-purpose operating systems choose the ostrich approach for user processes.
  • With single-instance resources, detection is cycle search; colored DFS runs in O(V + E). With multiple-instance resources, the loop “a process whose request can be met from the free resources finishes and releases what it holds” is run on the structures E, A, C, R; its cost is O(m · n2).
  • Recovery is done by resource preemption, rollback, or termination, and always costs some lost work. If the same process is always chosen as the victim, starvation results.
  • In a safe state there is a sequence that finishes all processes even if every process makes its maximum request. An unsafe state is not a deadlock, but it carries no guarantee of completion.
  • The banker's algorithm pretends to grant each request and grants it if the new state is safe. A process is made to wait for two reasons: the resource is not available, or granting would make the state unsafe. Because it requires maximum needs to be known in advance, it is rarely used in practice.
  • Prevention breaks one of the conditions. The most effective method is lock ordering: if locks are acquired in an order common to everyone, no cycle can form. Backing off with tryLock breaks the no-preemption condition, but without a random wait it can lead to livelock.
  • 2PL serves serializability and can deadlock. Starvation is a consequence of policy and is cured by aging. The most common concurrency bugs are not deadlocks but atomicity and order violations.
  • In Java a deadlock is found, but not resolved, with jstack or ThreadMXBean. lockdep and ThreadSanitizer report a possible deadlock before any deadlock happens.
Table 7.18: Comparison of the four strategies.
ApproachWhen?Information neededPriceUsed in
Ignoring—noneoccasional restartsgeneral-purpose operating systems
Detection and recoveryafterwardscurrent allocations and requestsperiodic O(m · n2), lost workdatabases, JVM tools
Avoidanceat every requestmaximum needs (Max)postponements, O(m · n2) per requestrarely, special systems
Preventionat design timeresource orderloss of flexibility and utilizationkernels, application code

7.11Key terms

  • deadlock
  • preemptable / nonpreemptable resource
  • Coffman conditions
  • mutual exclusion
  • hold and wait
  • no preemption
  • circular wait
  • resource-allocation graph
  • wait-for graph
  • deadlock detection
  • deadlock recovery
  • checkpoint
  • deadlock avoidance
  • safe / unsafe state
  • banker's algorithm
  • deadlock prevention
  • spooling
  • mutex
  • semaphore
  • monitor
  • busy waiting
  • two-phase locking (2PL)
  • livelock
  • starvation
  • aging
  • atomic instruction

7.12Test Yourself

  1. In a system, processes acquire locks with trylock. A process that cannot get the second lock releases the lock it holds and always waits exactly 5 ms before retrying. Which deadlock condition has been broken? What new problem can arise in this design, and how is it remedied?

    Answer

    Instead of waiting, the process releases the resource it holds of its own accord; the resource has in effect been taken back from its owner. This is a voluntary breaking of the no-preemption condition. If two processes acquire and release in the same rhythm, neither makes progress: livelock. The processes are not blocked; they use CPU time. The remedy is to make the wait time random and to increase it after each failure (exponential backoff), or to acquire the locks in a common order.

  2. In a wait-for graph the edges are P1 → P2, P2 → P3, P2 → P4, P4 → P5, and P5 → P3. Colored DFS starts at P1 and tries neighbors in numerical order. Is a cycle found? In what order are the nodes colored black?

    Answer

    P1, P2, P3 are colored gray in turn. P3 has no neighbors; the first black node is P3. P2's next neighbor, P4, is white; P4 and then P5 become gray. P5's only neighbor, P3, is black; an edge to a black node is not a cycle. P5 turns black, followed by P4, P2, and P1. The order of blackening is P3, P5, P4, P2, P1, and cycle returns false: there is no cycle. The edge P5 → P3 only shows that two paths merge at P3.

  3. There are three resource types and E = (3 2 2). The allocations are P1 (1 0 1), P2 (1 1 0), P3 (0 1 1); the requests are P1 (1 1 0), P2 (0 0 1), P3 (1 0 0). If the detection algorithm is run, rescanning from the beginning after each marking, does the system come out deadlocked? What would happen if P3's request were (1 0 1)?

    Answer

    The allocations sum to (2 2 2); A = (1 0 0). P1 (1 1 0) asks for the second type, and none is free. P2 (0 0 1) asks for the third type, and none is free. P3 (1 0 0) ≤ (1 0 0) ✓; P3 finishes and A = (1 1 1). From the start again: P1 (1 1 0) ≤ (1 1 1) ✓, A = (2 1 2). P2 (0 0 1) ✓, A = (3 2 2) = E. The order is P3, P1, P2; there is no deadlock. If P3's request were (1 0 1), then with A = (1 0 0) none of the three rows could be satisfied, and all three processes would be deadlocked.

  4. There are 12 units of a single resource type. A holds 5 units (at most 10), B holds 2 (at most 4), C holds 2 (at most 9). Is the state safe? Which are the safe sequences? In this state, if C asks for one more unit, should the request be granted?

    Answer

    There are 12 − 9 = 3 units free. The remaining needs are A 5, B 2, C 7. Only B can be satisfied (2 ≤ 3); B finishes and free becomes 5. Then only A can be satisfied (5 ≤ 5); A finishes and free becomes 10. Finally C (7 ≤ 10) finishes. The only safe sequence is ⟨B, A, C⟩; the state is safe. If C is given 1 unit, free is 2 and the needs are A 5, B 2, C 6. B finishes and free rises to 4; but neither A's 5 nor C's 6 can be met. The state is unsafe; the request is refused and C is made to wait.

  5. Five processes request resources of the same type one at a time; each uses at most 3 instances at once and releases them all when finished. What is the smallest number of instances that guarantees deadlock never occurs? How does one fewer lead to deadlock?

    Answer

    In the worst case each process holds 2 instances and waits for a third: 5 · 2 = 10 instances. If there is one more instance, one of the processes gets its third, finishes, and releases 3 instances; the others finish in turn. At least 5 · 2 + 1 = 11 instances are needed. With 10 instances each of the five processes can hold two; no instance is left free and everyone waits for a third: deadlock.

  6. In the initial state of the Silberschatz example (Available = (3 3 2)), T4 requests (3 3 0). What does the banker's algorithm decide? In the same initial state, what would the decision be if T0 requested (0 2 0)?

    Answer

    T4: (3 3 0) ≤ Need4 = (4 3 1) and ≤ (3 3 2); both checks pass. In the pretend state Available = (0 0 2) and Need4 = (1 0 1). None of the rows T0 (7 4 3), T1 (1 2 2), T2 (6 0 0), T3 (0 1 1), and T4 (1 0 1) can be satisfied with (0 0 2): the state is unsafe and the request is refused. T0: in the pretend state Available = (3 1 2) and Need0 = (7 2 3). T3 (0 1 1) finishes → (5 2 3); T1 (1 2 2) → (7 2 3); T2 (6 0 0) → (10 2 5); T0 (7 2 3) → (10 5 5); T4 (4 3 1) → (10 5 7). The safe sequence ⟨T3, T1, T2, T0, T4⟩ exists; the request is granted. The same request was refused after T1's request (1 0 2): the decision depends not on the request itself but on the whole state.

  7. In a program, the function transfer(a, b) acquires locks in order of account number. The function report(acct1, acct2) in the same program always acquires the locks of two accounts in the order acct1 first, then acct2. Can the program deadlock? Why?

    Answer

    It can. Lock ordering prevents cycles only if it is applied everywhere the locks are acquired. A call report(y, x) can hold y and request x. If at the same time transfer holds x in numerical order and requests y, a cycle forms. The remedy is to make report follow the same order. Tools such as lockdep or ThreadSanitizer report this reverse order without any deadlock ever occurring.

  8. In one Java server two threads have fallen into a livelock; in another server two threads are deadlocked. Which one does jstack report as “Found one Java-level deadlock”? How does CPU utilization look in the two cases?

    Answer

    jstack reports only the deadlock: the deadlocked threads are BLOCKED, and the wait-for graph built from monitor ownership contains a cycle. Threads in a livelock appear as RUNNABLE or, during short sleeps, TIMED_WAITING. Because they keep acquiring and releasing locks, there is no permanent cycle in the graph and no report is produced. In a deadlock CPU utilization drops, because the threads sleep. In a livelock the CPU looks busy but the work does not advance.

7.13Further reading

  • A. S. Tanenbaum and H. Bos, Modern Operating Systems (4th ed.), Chapter 6: treats the resource-allocation graph, the cycle-search and matrix-based detection algorithms, resource trajectories, and the banker's algorithm in detail, with the examples used in this chapter.
  • A. Silberschatz, P. B. Galvin, and G. Gagne, Operating System Concepts (10th ed., 2018), Chapter 8: gives the four conditions, the prevention protocols, and the safety and request parts of the banker's algorithm in pseudocode; it also introduces the Linux lockdep tool.
  • R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapter “Common Concurrency Problems”: describes atomicity and order violations, the four conditions for deadlock, and lock ordering with bugs taken from real systems. The book is online and free.
  • S. Lu, S. Park, E. Seo, and Y. Zhou, “Learning from Mistakes: A Comprehensive Study on Real World Concurrency Bug Characteristics,” ASPLOS 2008: a study that classifies 105 concurrency bugs in four large open-source projects and shows the weight of non-deadlock bugs.

7.14References

  1. R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, Arpaci-Dusseau Books, ostep.org — “Common Concurrency Problems”.
  2. E. G. Coffman, M. J. Elphick, A. Shoshani, “System Deadlocks”, ACM Computing Surveys 3(2), 1971.
  3. E. W. Dijkstra, “Cooperating Sequential Processes”, EWD-123, 1965.
  4. R. C. Holt, “Some Deadlock Properties of Computer Systems”, ACM Computing Surveys 4(3), 1972.
  5. Linux kernel documentation: Documentation/locking/lockdep-design.rst.
  6. S. Lu, S. Park, E. Seo, Y. Zhou, “Learning from Mistakes: A Comprehensive Study on Real World Concurrency Bug Characteristics”, ASPLOS 2008.
  7. Java SE 21 API documentation: java.lang.management.ThreadMXBean, java.util.concurrent.locks.ReentrantLock; the jstack manual.
  8. PostgreSQL documentation: “Explicit Locking — Deadlocks”, deadlock_timeout.
  9. A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 — Chapter 8: Deadlocks.
  10. A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed., Pearson, 2014 (5th ed. 2023) — Chapter 6: Deadlocks.

Related pages: Chapter 7 slides · © Sercan Külcü. All rights reserved.