Sub topic 5
Four ways to handle deadlock
This chapter assumes you know the resource model (processes, resource types, instances, request-use-release) and the four Coffman conditions: mutual exclusion, hold and wait, no preemption, and circular wait. You should also be comfortable with directed graphs and with comparing vectors element by element. Here we compare the four strategies at a high level. Later chapters work out the algorithms in detail.
The strategy question
The Coffman conditions say that all four must hold at once for a deadlock to occur. That gives an operating system four possible responses:
- Prevention: make sure at least one condition can never hold.
- Avoidance: allow all four conditions to be possible, but refuse any allocation that could lead to a deadlock.
- Detection and recovery: let deadlocks happen, notice them, and break them.
- Ignoring: do nothing and accept that deadlocks may occur.
The first two are called deadlock-prevention schemes in a broad sense, because the system never enters a deadlock. The third lets the system enter a deadlock and then leave it. The fourth is a deliberate decision not to spend effort on the problem.
A real system uses only some of these stages. A system that uses prevention does not need the avoidance test. A system that only detects skips both earlier tests and grants every request that can be satisfied.
Prevention
Prevention attacks the conditions themselves, and it works by adding rules for how processes may ask for resources. Each rule negates one condition.
| Condition negated | Typical rule | Main cost |
|---|---|---|
| Mutual exclusion | Make resources shareable (for example, read-only files) | Impossible for inherently non-shareable resources such as a printer |
| Hold and wait | Request all resources at once, or request only when holding none | Low utilization, and starvation of processes that need popular resources |
| No preemption | If a request fails, the process releases everything it holds | Only works for resources whose state can be saved and restored |
| Circular wait | Number the resource types and require requests in increasing order | Programmers must follow the order, and the order may not suit every program |
Resource ordering is the most practical of these. Locks in application code are the usual example. If every thread takes lock_a before lock_b, no cycle of waiting threads can form.
Prevention is conservative. It forbids some request patterns that would never have deadlocked, so it pays a price in utilization and flexibility on every run, even when deadlock was unlikely. The benefit is that the policy needs no run-time bookkeeping beyond checking the rule.
The next code example breaks "no preemption" voluntarily. A thread that cannot get its second lock within a timeout releases the first one and retries after a random pause. The random pause stops two threads from retrying in lockstep, which would be a livelock.
import random
import threading
import time
lock_a = threading.Lock()
lock_b = threading.Lock()
def worker(first, second, name, results):
for attempt in range(10):
with first:
time.sleep(0.05) # widen the window in which a conflict can occur
if second.acquire(timeout=0.1):
try:
results[name] = attempt + 1
return
finally:
second.release()
# Could not get the second lock: the first was released by the with block.
time.sleep(random.uniform(0.01, 0.1))
results[name] = None # gave up
results = {}
t1 = threading.Thread(target=worker, args=(lock_a, lock_b, "t1", results))
t2 = threading.Thread(target=worker, args=(lock_b, lock_a, "t2", results))
t1.start()
t2.start()
t1.join()
t2.join()
print(results) # each value is the attempt number on which the thread succeededThe two threads take the locks in opposite orders, so a plain implementation could deadlock. Here each thread gives up its first lock when it times out, and the program ends. The attempt numbers vary from run to run.
Avoidance
Avoidance does not restrict how a process asks. It restricts when a request is granted. The system looks at each request and asks whether granting it leaves the system in a safe state, meaning there is some order in which all processes can run to completion even if each demands its declared maximum.
Avoidance needs information that prevention does not:
- Each process must declare, before it starts, the maximum number of instances of each resource type it may ever need.
- The system must know how many instances each process holds and how many are free.
With that information the system can run the safety algorithm on a hypothetical state. For multiple instances this is the Banker's algorithm. For a single instance per resource type, claim edges in a resource-allocation graph do the same job.
Three facts about states are worth fixing now, because GATE questions test them directly:
- A safe state is never deadlocked.
- A deadlocked state is always unsafe.
- An unsafe state is not necessarily deadlocked. It only means the system can no longer guarantee that deadlock is avoided. Whether deadlock really happens depends on what the processes request next.
Avoidance is less conservative than prevention, since it grants any request that keeps the state safe. It is also costlier at run time, because every request triggers a safety check. Its main practical weakness is the requirement for advance maximum claims, which most general-purpose programs cannot provide.
Detection and recovery
A detection system grants every request that can be satisfied. It then runs an algorithm that looks for deadlock:
- With one instance per resource type, it searches the wait-for graph for a cycle. A cycle is a deadlock.
- With multiple instances, it runs a matrix algorithm similar to the safety algorithm, using current requests instead of maximum needs.
How often to run detection is a design choice with a trade-off:
- Running at every request that cannot be granted immediately finds a deadlock the moment it forms and identifies the request that closed the cycle. It is the most expensive option.
- Running at fixed intervals, or when CPU utilization drops, is cheaper. The downside is that many cycles may have formed by then, and it is harder to say which request caused them. Deadlocked processes also hold their resources idle in the meantime.
Once a deadlock is found, recovery has two basic tools:
- Process termination: abort all deadlocked processes, or abort them one at a time until the cycle breaks.
- Resource preemption: take a resource from one process and give it to another. This needs a victim-selection rule, rollback to a safe point, and protection against the same process always being chosen (starvation).
Detection costs nothing when no deadlock occurs, apart from the periodic check. Recovery, on the other hand, can be painful. Killing a process may leave files half-written, and rolling back a transaction wastes work.
Ignoring the problem
The fourth option is to assume that deadlocks are rare and do nothing. This is sometimes called the ostrich algorithm. Most general-purpose operating systems, including Unix-like systems and Windows, handle kernel-level resources this way for many cases. They leave deadlocks among user processes to application programmers.
The reasoning is a cost comparison. If deadlock happens once a year and a reboot fixes it, then a global rule that slows every request or demands advance claims is a bad deal. The choice is different for a system where a stuck process is expensive, such as a database engine or a flight controller. Database engines typically detect deadlocks and abort one transaction.
Comparing the strategies
| Strategy | Deadlock possible? | Needs advance information? | Run-time cost | Main weakness |
|---|---|---|---|---|
| Prevention | No | No | Low (rule check) | Low utilization, restricted programming |
| Avoidance | No | Yes (maximum claims) | Safety check per request | Claims are often unknown |
| Detection and recovery | Yes, temporarily | No | Periodic detection plus recovery work | Lost work from termination or rollback |
| Ignoring | Yes | No | None | System may hang until someone intervenes |
Systems often combine strategies. One common approach is to order the resource classes (prevention across classes) and use a different technique within each class, such as avoidance for memory and detection for files.
Exercise
A system grants a request only if the resulting state is safe. A process later makes a request that would leave the system in an unsafe state, though no deadlock exists yet. What does the system do, and does it mean deadlock would certainly have occurred?
Show answer
The system delays the request, so the process waits and the resources stay free. The state was only unsafe, not deadlocked, so deadlock would not certainly have occurred. Avoidance is conservative: it refuses any grant that removes the guarantee that all processes can finish.
Exercise
For each situation, name the strategy it belongs to: (a) every thread must lock mutexes in increasing order of their ID; (b) the OS runs a cycle check on a wait-for graph every 10 minutes; (c) each process declares its maximum resource need when it starts, and the OS tests every request against it; (d) a database aborts one transaction when it finds two transactions waiting on each other.
Show answer
(a) Prevention, because it negates circular wait. (b) Detection. (c) Avoidance. (d) Detection and recovery, with process termination as the recovery method.