flowchart TD A["Deadlock"] -->|circular wait| B["Threads wait<br/>for each other"] C["Livelock"] -->|retry interference| D["Threads execute<br/>but no progress"] E["Starvation"] -->|unfair allocation| F["One ready thread<br/>keeps losing out"]
8.10 Deadlock, Livelock, and Starvation
8.10.1 Motivation
A parallel system can fail in three ways that look like hanging but have different causes. Deadlock: threads wait for each other in a cycle. Livelock: threads execute but never make progress. Starvation: one thread could make progress but keeps losing the CPU or a lock to others. Each has different symptoms and different fixes, so the first step in debugging a stuck program is to find out which one it is.
8.10.2 Deadlock
Deadlock is circular wait. Thread A holds Lock 1 and waits for Lock 2. Thread B holds Lock 2 and waits for Lock 1. Neither releases. Both wait forever.
The four necessary conditions
Coffman, Elphick and Shoshani (1971) listed four conditions that must all hold for deadlock:
- Mutual exclusion: Only one thread can hold a resource.
- Hold and wait: A thread holds a resource and waits for another.
- No preemption: A thread cannot forcibly take a held resource.
- Circular wait: A cycle exists where each thread waits for the next.
Breaking any one condition prevents deadlock.
A concrete example
# Thread A
lock(lock1)
do_work_1()
lock(lock2)
unlock(lock2)
unlock(lock1)
# Thread B
lock(lock2)
do_work_2()
lock(lock1)
unlock(lock1)
unlock(lock2)If Thread A acquires Lock 1 and then Thread B acquires Lock 2, both threads block: A waits for Lock 2 while B waits for Lock 1. That cycle is the circular wait, and neither thread can break it.
Prevention: lock ordering
The practical fix is lock ordering. Define a strict order for acquiring locks. All code paths must respect the order.
// Global lock order: lock1 must come before lock2
correct_code():
lock(lock1)
lock(lock2)
do_work()
unlock(lock2)
unlock(lock1)
wrong_code():
lock(lock2) // Violates order! Can deadlock
lock(lock1)
do_work()
unlock(lock1)
unlock(lock2)If every thread acquires locks in the same order, no circular wait can form. Deadlock prevention becomes a code review discipline: enforce lock order everywhere.
In R: the fork-with-held-lock hazard
A dangerous case arises when one thread of a process holds a mutex while another thread calls fork().
# Parent process, thread T2
lock(shared_lock)
do_work() # T2 is inside the critical section
# Parent process, thread T1, at the same moment
result <- fork()
if (result == 0) {
# Child process: only a copy of T1 exists here
# shared_lock is still marked as held, by T2, which was not copied
lock(shared_lock) # waits forever
}The child inherits a held lock. POSIX creates the child with a single thread, a copy of the one that called fork(), so the thread that held the lock in the parent does not exist in the child. If the child tries to acquire the same lock, it waits for a thread that will never release it.
POSIX documents this hazard. The fork() page says the child of a multithreaded process holds a replica of the calling thread only, “possibly including the states of mutexes”, and may call only async-signal-safe functions until it calls exec. pthread_atfork() was meant as the fix: a prepare handler acquires every lock before the fork, and handlers in the parent and the child release them afterwards. Its own rationale calls this “good in theory, but in reality not practical”, and POSIX.1-2024 marks pthread_atfork() obsolescent.
R’s documentation names the same risk. ?mcfork in the parallel package says using mcfork and the functions built on it, mclapply() among them, is “strongly discouraged” in any R process with extra threads from a library or package, because the child “may not be able to access resources locked in the parent”. A multithreaded BLAS, or OpenMP code that has already run in the parent, is a common source of such threads.
8.10.3 Livelock
Livelock is progress-free activity. Threads execute but never accomplish work. They interfere with each other, retry, interfere again, in an endless loop.
A simple example
// Threads A and B both try to acquire two locks
// Both spin, yield, and retry, never making progress
thread_a_loop():
try:
lock(lock1)
try:
lock(lock2)
except:
unlock(lock1)
yield()
except:
yield()
thread_b_loop():
try:
lock(lock2)
try:
lock(lock1)
except:
unlock(lock2)
yield()
except:
yield()Thread A acquires Lock 1. Thread B acquires Lock 2. Thread A tries Lock 2, fails, releases Lock 1. Thread B tries Lock 1, fails, releases Lock 2. Both yield. Both retry. The pattern repeats forever. No work happens.
Livelock is harder to spot than deadlock because nothing looks stuck: the threads are running and CPU usage is high, yet no work completes.
Prevention: backoff and randomness
Add random exponential backoff to livelock-prone code. When a thread fails to acquire locks, it waits a random duration before retrying, and doubles the range of that wait after each failure. The two retry loops fall out of step, and soon one thread gets both locks and makes progress.
thread_a():
backoff = 10 // ms, upper bound of the first wait
loop:
try:
lock(lock1)
try:
lock(lock2)
do_work()
return
except:
unlock(lock1)
except:
pass
sleep(random_ms(1, backoff))
backoff = backoff * 2 // ExponentialBackoff makes a long livelock unlikely, not impossible: two threads can still pick similar delays a few times in a row, but the chance of that falls with every retry.
8.10.4 Starvation
Starvation is unfair allocation. A thread is ready to make progress, and it is not stuck in a cycle, but something keeps choosing other threads: the scheduler for the CPU, or a lock for its holder.
A scheduling example
A kernel scheduler manages three threads and two CPU cores. Threads A and B always have work. Thread C has occasional work. If A and B run at a higher fixed priority, for example under the real-time policy SCHED_FIFO, C runs only in the small share of CPU time that Linux holds back for ordinary threads, 5 percent by default, while they stay busy. Thread C is starved.
A lock can do the same. Many mutexes make no fairness promise: when the holder unlocks and immediately locks again, it can win the lock before the woken waiter gets scheduled. A thread in a tight lock and unlock loop can keep the lock for a long time while a waiter that arrived first keeps losing.
R’s GC interaction
GNU R runs R code on one thread per process, so the case below cannot arise in R today. It would arise in any runtime where several threads allocate from one shared heap, and there a garbage collection pause can starve a thread in effect.
# Three threads
# Thread 1 and 2 do heavy allocation
# Thread 3 does computation but needs small allocations
# Thread 1 fills the heap, triggering GC
# GC stops all threads
# GC runs on Thread 1's core
# Thread 2 and 3 are parked
# GC releases
# Thread 1 and 2 continue
# Thread 3 allocates a tiny object
# Heap is full again, GC triggered
# Thread 3 is starved by GC pausesThread 3 is not blocked by a lock. It is held up by GC pauses that other threads trigger. Each pause stops every thread equally, so the scheduling is fair, yet Thread 3 gets so little time between pauses that it behaves as if starved.
Prevention: fair scheduling and priorities
Use a fair scheduling policy. On Linux the default policy, SCHED_OTHER, is a fair-share scheduler (CFS, replaced by EEVDF in Linux 6.6), which the sched(7) man page says gives “fair progress among all SCHED_OTHER threads”. The POSIX real-time policies are the opposite case. SCHED_FIFO and SCHED_RR use fixed priorities, and SCHED_RR rotates only among threads of the same priority, so a busy high-priority thread under either policy can starve every thread below it.
Raising the priority of the starved work is the other lever. It moves the risk of starvation to the threads that are now ranked lower, and it does nothing against the GC pauses above, since a stop-the-world pause stops every thread whatever its priority.
8.10.5 Interaction and diagnosis
Diagnosing deadlock
The affected threads stop making progress, and in a small program that can look like a complete hang. A thread dump or debugger shows threads blocked on mutex acquisitions, waiting for each other in a cycle.
Diagnosing livelock
The system is busy (high CPU). Threads are not blocked. A debugger shows threads executing but stuck in retry loops. Progress is zero.
Diagnosing starvation
The system makes progress, but unevenly. One thread’s work advances slowly while others are fast. Profiling shows unequal CPU time.
8.10.6 Prevention summary
| Failure | Cause | Fix |
|---|---|---|
| Deadlock | Circular wait for locks | Lock ordering, avoid nested locks |
| Livelock | Retry loop interference | Random backoff, exponential delays |
| Starvation | Unfair scheduling or lock handoff | Fair scheduling policy, fair locks, priorities |
Three failure modes: deadlock is blocked circular wait, livelock is active no-progress loops, starvation is unfair allocation of the CPU or a lock.
Further reading
- “The Little Book of Semaphores” by Allen B. Downey. Free online. Covers classic synchronization problems and their deadlock traps. https://greenteapress.com/wp/semaphores/
- Stallings, W. (2018). Operating Systems: Internals and Design Principles (9th ed.). Pearson. Chapters on deadlock detection and avoidance.
- POSIX specification for
pthread_atfork(), whose rationale explains why the handlers fall short: https://pubs.opengroup.org/onlinepubs/9799919799/functions/pthread_atfork.html - Coffman, E. G., Elphick, M. J., & Shoshani, A. (1971). System deadlocks. ACM Computing Surveys, 3(2), 67-78. Foundational paper on the four necessary conditions. https://doi.org/10.1145/356586.356588
Where this appears
- threaded-r Lock ordering across shared symbol tables, scheduler queues, and interpreter state is critical to prevent deadlock in multi-interpreter systems.