Sub topic 2
What a deadlock is, and what it is not
This chapter assumes you know what processes and threads are, and how locks or semaphores enforce mutual exclusion. It also assumes you have seen the request, use, release cycle on resources from the previous chapter. Here we pin down the definition of deadlock and separate it from two conditions that look similar: starvation and livelock. GATE questions often test exactly this boundary.
The definition
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 cause. In a resource system, the event is almost always "a resource is released."
Four parts of this definition matter.
- It is a property of a set. One process can be deadlocked only with itself (see the self-deadlock case below). Usually the set has two or more members.
- Every member is blocked. None of them can run, so none can release what it holds.
- The wait is circular in effect. The event each process needs can come only from inside the set, so nobody outside can unblock them.
- It is permanent. Without outside intervention, such as killing a process or taking a resource away, the wait never ends.
The classic two-process case: P1 holds R1 and requests R2, while P2 holds R2 and requests R1. Neither request can be satisfied until the other process releases, and neither process will release before it finishes.
A deadlock you can run
The program below forces the bad interleaving with a barrier, so it deadlocks every time. It uses a timeout on the second lock so the demo reports the deadlock and exits instead of hanging. Production code that waits forever would simply freeze.
import threading
lock_a = threading.Lock()
lock_b = threading.Lock()
both_hold_first = threading.Barrier(2)
both_tried_second = threading.Barrier(2)
def worker(name, first, second):
with first:
both_hold_first.wait() # make sure each thread holds its first lock
got = second.acquire(timeout=1)
if got:
print(name, "got both locks")
else:
print(name, "timed out waiting for its second lock: deadlock")
both_tried_second.wait() # nobody releases until both have tried
if got:
second.release()
t1 = threading.Thread(target=worker, args=("T1", lock_a, lock_b))
t2 = threading.Thread(target=worker, args=("T2", lock_b, lock_a))
t1.start()
t2.start()
t1.join()
t2.join()Both threads print the timeout message (the order may vary). The second barrier keeps either thread from releasing its first lock while the other is still waiting. Without it, one thread's timeout could free a lock and let the other thread succeed, which would hide the deadlock.
Deadlock needs no unusual resources
Deadlock is not limited to hardware devices. Anything that is requested, held, and released can take part:
- mutex locks, semaphores, and monitors
- files, database rows, and memory buffers
- message-queue slots and pipe buffers
When the "resource" is a message rather than a lock, the situation is called a communication deadlock. For example, two processes each block on a receive from the other. The definition applies unchanged: each waits for an event only the other can cause.
Self-deadlock
A single thread can deadlock itself. If a thread acquires a non-reentrant lock and then tries to acquire the same lock again, it waits for a release that only it could perform.
import threading
lock = threading.Lock()
lock.acquire()
ok = lock.acquire(timeout=0.5) # same thread, same non-reentrant lock
print(ok) # False: the thread is waiting on itselfA reentrant lock (threading.RLock in Python) avoids this case by letting the owner acquire it again.
Deadlock is a state, and not every long wait is one
A process waiting on a slow disk, a busy lock, or user input is not deadlocked. Its wait will end by itself, because the event it needs can come from something that is still running. Deadlock requires that the set of waiters is closed: no running process can end the wait.
Two relationships connect deadlock to later chapters. Both use terms defined there.
- A deadlocked state is always an unsafe state, but an unsafe state is not necessarily deadlocked. Avoidance algorithms work by keeping the system out of unsafe states, which is stricter than only avoiding deadlock.
- A cycle in a resource-allocation graph is necessary for deadlock but not always sufficient. With multiple instances per resource type, a cycle may exist without a deadlock.
Starvation
Starvation (also called indefinite blocking) means a process waits for a very long or unbounded time while the system as a whole keeps making progress. The process is ready to run or is waiting for a resource, but the scheduling or allocation policy keeps choosing others.
Typical causes:
- Priority scheduling where high-priority processes keep arriving, so a low-priority process never gets the CPU.
- A resource allocator that always favors short requests, so a large request never fits.
- Readers that keep arriving in a readers-writers solution that favors readers, so a writer never enters.
Starvation differs from deadlock in three ways.
- Other processes are not blocked. They run and finish normally.
- The starving process's wait could end if the policy changed. Nothing is structurally stuck.
- The standard fix is a policy change, such as aging, which raises a process's priority the longer it waits. Deadlock needs prevention, avoidance, or recovery instead.
Deadlock implies starvation of the deadlocked processes, since they wait forever. The reverse is false: a starving process is not part of a closed waiting set.
Livelock
Livelock means processes keep changing state in response to each other but make no useful progress. Unlike deadlock, they are not blocked. They run and consume CPU.
The standard picture is two people meeting in a corridor. Each steps aside to let the other pass, both step to the same side again, and they repeat forever. In software the pattern is a "polite" retry protocol:
import threading
import time
lock_a = threading.Lock()
lock_b = threading.Lock()
barrier = threading.Barrier(2)
attempts = {"T1": 0, "T2": 0}
def polite(name, first, second, rounds=5):
for _ in range(rounds):
first.acquire()
barrier.wait() # both threads hold their first lock
if second.acquire(blocking=False):
second.release()
first.release()
print(name, "finished")
return
first.release() # back off and try again
attempts[name] += 1
barrier.wait() # both back off together, then retry in lockstep
print(name, "gave up after", attempts[name], "failed rounds")
t1 = threading.Thread(target=polite, args=("T1", lock_a, lock_b))
t2 = threading.Thread(target=polite, args=("T2", lock_b, lock_a))
t1.start()
t2.start()
t1.join()
t2.join()Each thread holds one lock, fails to get the other, releases, and retries in exact lockstep. Both fail every round and report giving up. The barriers make the lockstep deterministic. In real systems, timing makes it likely but not certain, which is why randomized backoff (as in Ethernet) breaks livelock in practice.
Side-by-side comparison
| Property | Deadlock | Starvation | Livelock |
|---|---|---|---|
| Process state | Blocked (waiting) | Ready or waiting | Running, changing state |
| CPU use by the affected processes | None | Little or none | Wasted on useless work |
| Other processes | The deadlocked set cannot help each other, but unrelated processes proceed | Proceed normally | May also be affected |
| Does the wait end on its own? | No | Possibly, if the policy or load changes | Possibly, if timing changes |
| Cause | Closed circular waiting for resources | Unfair scheduling or allocation policy | Reactive retry or yield protocols |
| Typical fix | Prevention, avoidance, detection and recovery | Aging, fair queues | Randomized backoff, ordering, a tie-breaker |
The diagram below turns the table into a decision procedure.
Common errors
- "Deadlock means the system is frozen." Only the processes in the deadlocked set are stuck. The rest of the system can run normally, though it may later block on resources the deadlocked processes hold.
- "A long wait is a deadlock." A wait is a deadlock only if no remaining process can end it.
- "Livelock is a kind of deadlock where processes are blocked." In livelock the processes are not blocked. They use CPU time.
- "Aging fixes deadlock." Aging fixes starvation. A deadlocked process does not get a turn no matter how high its priority rises, because the resource it needs is held by a blocked process.
- "If the lock acquisition order differs between threads, deadlock must occur." Differing order makes deadlock possible but not certain. It occurs only under an unlucky interleaving, which is why such bugs appear intermittently.
Exercise
A low-priority process has been in the ready queue for hours because a stream of high-priority processes keeps arriving. Other processes run and complete normally. Is this a deadlock? Name the problem and one standard remedy.
Show answer
It is not a deadlock. The process is not part of a closed set waiting on each other, and it could run if the scheduler chose it. The problem is starvation, and the standard remedy is aging, which gradually raises the priority of a process the longer it waits.
Exercise
Two threads each call try-lock on two locks. When the second try-lock fails, each releases its first lock and retries immediately. Both keep looping and burning CPU with no work done. Which condition is this, and what change would likely break the pattern?
Show answer
This is livelock. The threads are running and changing state but make no progress. Adding a random backoff delay before retrying, or making both threads acquire the locks in the same fixed order, breaks the pattern.
Exercise
True or false: if a resource-allocation system contains a process that has waited for a very long time, the system is in a deadlock. Explain briefly.
Show answer
False. A long wait only means the process is delayed. Deadlock requires that the awaited event can be caused only by processes that are themselves blocked in a closed set. The process may simply be starved, or waiting for a resource that a running process will eventually release.