Conceptcore
Deadlock
Also called deadly embrace, circular wait.
A deadlock is a cycle of waits. Each thread in the cycle holds a resource and waits for a resource that the next thread holds, so no thread in the cycle can continue.
- Applies to
- core-languages
Idea
A deadlock is a state in which a group of threads wait for each other in a cycle. Thread t1 holds lock A and waits for lock B. Thread t2 holds lock B and waits for lock A. Each thread releases its lock only after it gets the other lock, so neither wait can end. The program does not crash and prints no error. It stops making progress.
The term is wider than threads and locks. Coffman, Elphick and Shoshani apply it to devices, storage, programs and data, and they quote Dijkstra's name for it, the "deadly embrace".1 A database transaction, a process or an async task can be part of a deadlock too.
In Python, two threads take two locks in opposite orders. A barrier makes sure that each thread has its first lock before either thread asks for its second lock. A real deadlock waits forever. Here the timeout argument of acquire ends each wait after 0.2 s, and acquire returns False.2
import threading
a = threading.Lock()
b = threading.Lock()
both_hold = threading.Barrier(2)
both_tried = threading.Barrier(2)
results = {}
def transfer(name, first, second):
with first:
both_hold.wait()
got = second.acquire(timeout=0.2)
if got:
second.release()
both_tried.wait()
results[name] = got
t1 = threading.Thread(target=transfer, args=("t1", a, b))
t2 = threading.Thread(target=transfer, args=("t2", b, a))
t1.start()
t2.start()
t1.join()
t2.join()
for name in sorted(results):
print(name, "got its second lock:", results[name])
t1 got its second lock: False
t2 got its second lock: False
The second barrier keeps each thread on its first lock until both threads have tried. Without it, one thread could time out, release its lock, and let the other thread through. The output would then change from run to run. The fix is in How it works: take the locks in one global order.
How it works
The four conditions
Coffman, Elphick and Shoshani list four conditions that are all in effect when a deadlock exists.1
- Mutual exclusion. A task claims exclusive control of the resources it needs. A lock is the usual example: one thread at a time holds it.
- Hold and wait. A task holds the resources that it already has while it waits for more. The paper calls this the "wait for" condition.
- No preemption. Nothing can take a resource away from the task that holds it. The task gives it back only when it is done.
- Circular wait. A circular chain of tasks exists, and each task holds a resource that the next task in the chain requests.
The first three conditions are properties of the resources and of the rules for their use. Most locks have all three. The fourth condition is a property of one moment in one run. A program can run correctly a thousand times and deadlock on the next run, when the threads reach their locks in an unlucky order. The paper says that the four conditions together "effectively" define a deadlock state.1
The wait-for graph
A graph shows the cycle. Coffman et al. use a state graph with one node for each resource. An arc goes from resource Rj to resource Rk when some task holds Rj and requests Rk. Take the case of one resource of each type. Then a deadlock exists at a time t if and only if the graph has a circuit at t.1 When there are several identical resources of a type, a circuit is necessary for a deadlock but not sufficient.
An equivalent graph puts the threads at the nodes. An arc goes from thread t1 to thread t2 when t1 waits for a resource that t2 holds. This is the wait-for graph, and a cycle in it is the deadlock. The run in Idea gives this graph:
t1 --waits for B, which t2 holds--> t2
t2 --waits for A, which t1 holds--> t1
The order of events that leads to it:
step thread t1 thread t2
1 lock A: granted
2 lock B: granted
3 lock B: wait (t2 holds B)
4 lock A: wait (t1 holds A)
t1 waits for t2 and t2 waits for t1: a cycle
The steps can also run as 1, 3, 2, 4. Then t1 gets both locks at step 3, and no deadlock occurs. The bug is in the program in both cases, but only some schedules show it.
Three ways to deal with deadlock
Coffman et al. sort the treatments into three groups.1
- Prevention. Design the program so that one of the four conditions can never hold.
- Detection and recovery. Let the deadlock happen, find the cycle, and break it, for example by aborting one of the tasks.
- Avoidance. Use advance information about the resources that each task will need, and refuse a request that could lead to a deadlock.
The sections below show each group, with the tools that languages and databases give for it.
Prevention: lock ordering
The paper gives three approaches from Havender, and each one denies one condition. Mutual exclusion stays, because a lock exists to give exclusive access.1
The third approach of Havender is a linear order of resources. A task that holds a resource may then ask only for resources that come later in the order. With this rule, the state graph cannot have a circuit, so circular wait is impossible.1 In code, every thread takes its locks in one global order. The key can be an account number, an address, or a rank in a lock hierarchy.
import threading
class Account:
def __init__(self, number, balance):
self.number = number
self.balance = balance
self.lock = threading.Lock()
def transfer(source, target, amount):
first, second = sorted((source, target), key=lambda acc: acc.number)
with first.lock, second.lock:
source.balance -= amount
target.balance += amount
a = Account(1, 1000)
b = Account(2, 1000)
def many(source, target, amount):
for _ in range(500):
transfer(source, target, amount)
threads = [
threading.Thread(target=many, args=(a, b, 1)),
threading.Thread(target=many, args=(b, a, 2)),
]
for t in threads:
t.start()
for t in threads:
t.join()
print("a:", a.balance, "b:", b.balance, "total:", a.balance + b.balance)
a: 1500 b: 500 total: 2000
The call transfer(b, a, 2) names the accounts in the opposite order, but it still locks account 1 first. Havender used this method in OS/360: the system acquired storage, devices and data sets for each job step in a fixed order.1 The order must be total and every code path must follow it. One function that locks in another order brings the deadlock back.
Prevention: take all the locks at once
Havender's first approach denies hold and wait. A task requests all its resources at once and waits until it gets all of them.1 C++ has this in its library. std::lock(m1, m2, ...) locks all its arguments and "does not result in deadlock". The standard leaves its algorithm unspecified.3 std::scoped_lock calls std::lock in its constructor and unlocks all the mutexes in its destructor.4 Two threads can then name the same two mutexes in opposite orders, and the program still does not deadlock (see the C++ example).
The cost is that a task must know all its resources before it starts. The paper also notes that resources can stay allocated and unused for long periods.1
Prevention: try, back off and retry
Havender's second approach denies no preemption. A task that cannot get a further resource releases what it holds, then asks for all of it again.1 With locks, the program uses a try-lock or a timed lock:
| Language | Try or timed lock | Result when the lock is not free |
|---|---|---|
| Python | lock.acquire(timeout=0.2) |
returns False2 |
| Java, Kotlin | ReentrantLock.tryLock(200, MILLISECONDS) |
returns false5 |
| C# | Monitor.TryEnter(obj, TimeSpan) |
returns false6 |
| C, POSIX | pthread_mutex_trylock |
returns EBUSY7 |
| C++ | std::timed_mutex::try_lock_for |
returns false8 |
| Rust | Mutex::try_lock |
returns Err(TryLockError::WouldBlock)9 |
The thread that fails releases its first lock, waits a short time, and starts again. The Kotlin example does this. The wait matters: two threads that retry at the same rhythm can collide again and again (see livelock in Variations).
Avoidance: the banker's algorithm
Avoidance needs advance information about the resource use of each task.1 Dijkstra described the banker's algorithm in section 6.1 of "Cooperating Sequential Processes", in the chapter on the deadly embrace.10 Coffman et al. describe a model of the same kind from Habermann. Each task declares the maximum number of resources of each type that it can need. A state is safe when some order exists in which all the running tasks can get their maximum and finish. The system grants a request only when the state after the grant is still safe.1
The method needs the maximum needs of each task in advance, and a program that locks objects often does not know them. Dijkstra's EWD 623 gives the mathematics of the algorithm.11
Detection
Detection builds the wait-for graph and looks for a cycle. With one resource of each type, a detector updates the graph at each request, grant and release. Then it checks the graph for a circuit.1 Recovery then breaks the cycle, for example by aborting the tasks in the cycle one at a time until the rest can continue.1
- Java.
ThreadMXBean.findDeadlockedThreads()finds cycles of platform threads that wait for object monitors or for ownable synchronizers such asReentrantLock. It returns the IDs of the threads, ornull. Cycles that contain virtual threads are not found. The method is for troubleshooting, not for synchronization control, and it "might be an expensive operation".12 Thejstacktool prints the stack traces of the threads of a running JVM, and-ladds information about locks.13 The Java language itself "neither prevents nor requires detection of deadlock conditions".14 - Go. The runtime counts the threads that run Go code. When the count is zero and no timer is pending, it stops the program with
fatal error: all goroutines are asleep - deadlock!.15 The check sees only the whole program. Two goroutines that wait for each other while a third goroutine still runs are not found (see the Go example). - Databases. PostgreSQL detects a deadlock between transactions and aborts one of them. Which one is "difficult to predict". The documentation tells programs to acquire locks in a consistent order and to retry a transaction that was aborted.16 The check is "relatively expensive", so the server waits for
deadlock_timeout, 1 s by default, before it runs it.17
The Java detector finds the cycle from the Idea, with the threads still blocked. The example stops by itself because the two threads are daemon threads.
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
public class Main {
static Thread worker(String name, Object first, Object second, CountDownLatch ready) {
Thread t = new Thread(() -> {
synchronized (first) {
ready.countDown();
try {
ready.await();
} catch (InterruptedException e) {
return;
}
synchronized (second) {
System.out.println(name + " has both locks");
}
}
}, name);
t.setDaemon(true);
return t;
}
public static void main(String[] args) throws InterruptedException {
Object a = new Object();
Object b = new Object();
CountDownLatch ready = new CountDownLatch(2);
worker("t1", a, b, ready).start();
worker("t2", b, a, ready).start();
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] ids = null;
for (int i = 0; i < 100 && ids == null; i++) {
Thread.sleep(10);
ids = bean.findDeadlockedThreads();
}
String[] names = Arrays.stream(bean.getThreadInfo(ids))
.map(info -> info.getThreadName())
.sorted()
.toArray(String[]::new);
System.out.println("deadlocked: " + String.join(", ", names));
}
}
deadlocked: t1, t2
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Native | |
| C | Standard library | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Standard library | |
| SQL | Native | Transactions that lock the same rows in opposite orders deadlock; PostgreSQL detects the cycle and aborts one transaction. Alternative: Lock rows in a consistent order, and retry a transaction that the server aborted. |
| Bash | Absent | The shell has no threads and no locks. Alternative: Processes that wait for each other, through pipes, wait or lock files, can still deadlock; take lock files in one fixed order. |
| PowerShell | Standard library | |
| HTML | Does not apply | Markup has no threads and no waits. |
| CSS | Does not apply | Style rules have no threads and no waits. |
| Regular expressions | Does not apply | A pattern has no threads and no waits. |
Every language with threads and locks can deadlock, and so can every language with a blocking wait of some other kind. The verdict says where the program meets deadlock and which tools the language gives against it.
| Language | Verdict | Form |
|---|---|---|
| Python | stdlib | threading.Lock, RLock; acquire(timeout=...); Thread.join refuses a self-join |
| JavaScript | native | no shared-memory threads, but async functions can await each other in a cycle |
| TypeScript | native | as JavaScript |
| Java | native | synchronized monitors and java.util.concurrent.locks; ThreadMXBean finds cycles |
| C | stdlib | POSIX mutexes; an error-checking mutex reports a relock with EDEADLK |
| C++ | stdlib | std::mutex; std::lock and std::scoped_lock take several mutexes without deadlock |
| C# | native | the lock statement and Monitor.TryEnter with a timeout |
| Go | native | sync.Mutex and channels; the runtime stops a program in which all goroutines are asleep |
| Rust | stdlib | std::sync::Mutex with try_lock; safe code can deadlock |
| Kotlin | stdlib | the JDK locks, such as ReentrantLock.tryLock with a timeout |
| PowerShell | stdlib | .NET locks in parallel script blocks |
| Bash | absent | no threads or locks; processes that wait for each other can still deadlock |
| SQL | native | transactions that lock rows in opposite orders; the server detects the cycle |
| Regex | n/a | a pattern has no threads and no waits |
| HTML/CSS | n/a | markup and style have no threads and no waits |
The C examples use POSIX threads, because the C toolchain of the examples has no <threads.h>.
Rust does not prevent deadlocks. The Rust Reference lists deadlocks among the behaviours that are not considered unsafe, so safe code can deadlock.18 Data races are a different bug (see Data race).
import threading
def try_twice(lock):
with lock:
again = lock.acquire(timeout=0.2)
if again:
lock.release()
return again
print("Lock, second acquire:", try_twice(threading.Lock()))
print("RLock, second acquire:", try_twice(threading.RLock()))
Lock, second acquire: False
RLock, second acquire: True
- Verdict: stdlib. The
threadingmodule givesLock,RLock,Condition,SemaphoreandBarrier. Any of them can be part of a cycle of waits. - A
Lockhas no owner. A secondacquireby the same thread waits like any otheracquire, so the thread waits for itself. The timeout here ends the wait withFalse. - An
RLockknows its owner and counts the acquisitions. The owner can acquire it again, and it must release it as many times. acquire(timeout=...)andacquire(blocking=False)give the try-lock of the back off method.Thread.join(timeout=...)returns after the timeout, andis_alive()then tells if the thread is still running.
#include <iostream>
#include <mutex>
#include <thread>
struct Account {
int balance;
std::mutex m;
};
void transfer(Account& from, Account& to, int amount) {
std::scoped_lock lock(from.m, to.m);
from.balance -= amount;
to.balance += amount;
}
int main() {
Account a{1000, {}};
Account b{1000, {}};
std::thread t1([&] {
for (int i = 0; i < 10000; ++i) transfer(a, b, 1);
});
std::thread t2([&] {
for (int i = 0; i < 10000; ++i) transfer(b, a, 2);
});
t1.join();
t2.join();
std::cout << "a: " << a.balance << ", b: " << b.balance
<< ", total: " << a.balance + b.balance << '\n';
}
a: 11000, b: -9000, total: 2000
- Verdict: stdlib.
std::mutex,std::timed_mutexandstd::recursive_mutexare in<mutex>.std::lockandstd::scoped_locklock several mutexes without deadlock. - The two threads name the mutexes in opposite orders. Two
std::lock_guardobjects in that order could deadlock. Onestd::scoped_lockwith both mutexes does not, because it callsstd::lock. std::timed_mutex::try_lock_forgives a lock with a timeout for the back off method.- A second
lockof astd::mutexby the thread that owns it is undefined behaviour.std::recursive_mutexallows it.
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
static final CyclicBarrier bothHold = new CyclicBarrier(2);
static final CyclicBarrier bothTried = new CyclicBarrier(2);
static final boolean[] got = new boolean[2];
static Thread worker(int index, ReentrantLock first, ReentrantLock second) {
return new Thread(() -> {
first.lock();
try {
bothHold.await();
got[index] = second.tryLock(200, TimeUnit.MILLISECONDS);
if (got[index]) second.unlock();
bothTried.await();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
first.unlock();
}
});
}
public static void main(String[] args) throws InterruptedException {
ReentrantLock a = new ReentrantLock();
ReentrantLock b = new ReentrantLock();
Thread t1 = worker(0, a, b);
Thread t2 = worker(1, b, a);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("t1 got its second lock: " + got[0]);
System.out.println("t2 got its second lock: " + got[1]);
}
}
t1 got its second lock: false
t2 got its second lock: false
- Verdict: native.
synchronizedblocks lock the monitor of an object, and the language neither prevents nor detects deadlock.java.util.concurrent.locksaddsReentrantLockwithtryLockand a timeout. - A
synchronizedblock cannot time out. Code that needs the back off method usesReentrantLock, as here. ThreadMXBean.findDeadlockedThreads()finds a cycle of platform threads at run time (see the Java program in the node). Thejstack -ltool prints the threads and their locks.- Monitors and
ReentrantLockare reentrant, so a thread that takes the same lock twice does not deadlock.
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
int main(void) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_t m;
pthread_mutex_init(&m, &attr);
pthread_mutex_lock(&m);
int rc = pthread_mutex_lock(&m);
printf("second lock: %s\n", rc == EDEADLK ? "EDEADLK" : strerror(rc));
rc = pthread_mutex_trylock(&m);
printf("trylock: %s\n", rc == EBUSY ? "EBUSY" : strerror(rc));
pthread_mutex_unlock(&m);
rc = pthread_join(pthread_self(), NULL);
printf("self-join: %s\n", rc == EDEADLK ? "EDEADLK" : strerror(rc));
pthread_mutex_destroy(&m);
pthread_mutexattr_destroy(&attr);
return 0;
}
second lock: EDEADLK
trylock: EBUSY
self-join: EDEADLK
- Verdict: stdlib. The example uses POSIX threads. A
PTHREAD_MUTEX_NORMALmutex deadlocks when its owner locks it again. APTHREAD_MUTEX_ERRORCHECKmutex returnsEDEADLKinstead, and aPTHREAD_MUTEX_RECURSIVEmutex counts the locks. pthread_mutex_trylockreturnsEBUSYwhen the mutex is locked, also for its owner, unless the mutex is recursive. It is the try-lock for the back off method.- POSIX allows
pthread_jointo fail withEDEADLKwhen it detects a deadlock. The C library of the example returns it for a self-join, as Linux does.
using System;
using System.Threading;
var a = new object();
var b = new object();
using var bothHold = new Barrier(2);
using var bothTried = new Barrier(2);
var got = new bool[2];
Thread Worker(int index, object first, object second) => new Thread(() =>
{
lock (first)
{
bothHold.SignalAndWait();
got[index] = Monitor.TryEnter(second, TimeSpan.FromMilliseconds(200));
if (got[index]) Monitor.Exit(second);
bothTried.SignalAndWait();
}
});
var t1 = Worker(0, a, b);
var t2 = Worker(1, b, a);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine($"t1 got its second lock: {got[0]}");
Console.WriteLine($"t2 got its second lock: {got[1]}");
t1 got its second lock: False
t2 got its second lock: False
- Verdict: native. The
lockstatement takes the monitor of an object and releases it at the end of the block. It has no timeout, so a cycle oflockstatements waits forever. Monitor.TryEnterwith aTimeSpanreturnsfalsewhen the time runs out. It is the try-lock for the back off method.lockis reentrant: the thread that holds the lock can take it again.- The compiler rejects
awaitinside alockbody.
class Mutex {
#locked = false;
#waiters = [];
lock() {
if (!this.#locked) {
this.#locked = true;
return Promise.resolve();
}
return new Promise((resolve) => this.#waiters.push(resolve));
}
unlock() {
const next = this.#waiters.shift();
if (next) next();
else this.#locked = false;
}
}
const tick = () => new Promise((resolve) => setTimeout(resolve, 10));
const a = new Mutex();
const b = new Mutex();
async function transfer(name, first, second) {
await first.lock();
await tick();
await second.lock();
console.log(name, "has both locks");
second.unlock();
first.unlock();
}
const work = Promise.all([transfer("t1", a, b), transfer("t2", b, a)]);
const timeout = new Promise((resolve) =>
setTimeout(() => resolve("timeout"), 200),
);
console.log(await Promise.race([work.then(() => "done"), timeout]));
timeout
- Verdict: native. JavaScript has no threads that share a heap, but two async functions can wait for each other. Each
awaithere waits for a lock that the other function holds. - The cycle is silent. A promise that never settles uses no CPU and gives no error. The timer in
Promise.raceturns the wait into a result. - In Node.js, an ES module whose top-level
awaitnever settles ends with exit code 13:
This code fails on purpose. The output below is the error.
const never = new Promise(() => {});
await never;
console.log("not printed");
Node.js prints a warning about an unsettled top-level await, then exits with code 13.
class Mutex {
#locked = false;
#waiters: Array<() => void> = [];
lock(): Promise<void> {
if (!this.#locked) {
this.#locked = true;
return Promise.resolve();
}
return new Promise((resolve) => this.#waiters.push(resolve));
}
unlock(): void {
const next = this.#waiters.shift();
if (next) next();
else this.#locked = false;
}
}
interface Account {
id: number;
balance: number;
mutex: Mutex;
}
const tick = (): Promise<void> => new Promise((r) => setTimeout(r, 1));
async function transfer(from: Account, to: Account, amount: number) {
const [first, second] = from.id < to.id ? [from, to] : [to, from];
await first.mutex.lock();
await tick();
await second.mutex.lock();
from.balance -= amount;
to.balance += amount;
second.mutex.unlock();
first.mutex.unlock();
}
const a: Account = { id: 1, balance: 100, mutex: new Mutex() };
const b: Account = { id: 2, balance: 100, mutex: new Mutex() };
const jobs: Promise<void>[] = [];
for (let i = 0; i < 20; i++) {
jobs.push(transfer(a, b, 1), transfer(b, a, 2));
}
await Promise.all(jobs);
console.log(`a: ${a.balance}, b: ${b.balance}, total: ${a.balance + b.balance}`);
a: 120, b: 80, total: 200
- Verdict: native. TypeScript runs as JavaScript, so async functions can wait for each other in a cycle as in the JavaScript example.
- The fix is the same as with threads: every task takes the two locks in the order of the account ids. Without the order, the
await tick()between the locks would let the tasks deadlock. - The type checker does not see the order of locks, and it accepts a cycle of awaits.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var a, b sync.Mutex
var ready sync.WaitGroup
ready.Add(2)
worker := func(first, second *sync.Mutex) {
first.Lock()
ready.Done()
ready.Wait()
second.Lock()
}
go worker(&a, &b)
go worker(&b, &a)
done := make(chan struct{})
go func() {
ready.Wait()
a.Lock()
close(done)
}()
select {
case <-done:
fmt.Println("done")
case <-time.After(200 * time.Millisecond):
fmt.Println("timeout: the workers wait for each other")
}
}
timeout: the workers wait for each other
- Verdict: native. Goroutines block on
sync.Mutex, on channels and onsync.WaitGroup, and each of these waits can be part of a cycle. - The runtime stops a program in which no goroutine can run, with
fatal error: all goroutines are asleep - deadlock!and exit code 2. Here the timer oftime.Afteris pending, so the runtime check does not fire, and theselectreports the deadlock. Whenmainreturns, the blocked goroutines end with the program. - The same two workers with
wg.Wait()inmainand no timer stop with the runtime error:
This code fails on purpose. The output below is the error.
package main
import "sync"
func main() {
var a, b sync.Mutex
var ready, done sync.WaitGroup
ready.Add(2)
worker := func(first, second *sync.Mutex) {
defer done.Done()
first.Lock()
ready.Done()
ready.Wait()
second.Lock()
}
done.Add(2)
go worker(&a, &b)
go worker(&b, &a)
done.Wait()
}
use std::sync::{Arc, Barrier, Mutex, TryLockError};
use std::thread;
fn main() {
let a = Arc::new(Mutex::new(0));
let b = Arc::new(Mutex::new(0));
let both_hold = Arc::new(Barrier::new(2));
let both_tried = Arc::new(Barrier::new(2));
let spawn = |name: &'static str, first: Arc<Mutex<i32>>, second: Arc<Mutex<i32>>| {
let (hold, tried) = (Arc::clone(&both_hold), Arc::clone(&both_tried));
thread::spawn(move || {
let _guard = first.lock().unwrap();
hold.wait();
let busy = matches!(second.try_lock(), Err(TryLockError::WouldBlock));
tried.wait();
(name, busy)
})
};
let t1 = spawn("t1", Arc::clone(&a), Arc::clone(&b));
let t2 = spawn("t2", Arc::clone(&b), Arc::clone(&a));
for handle in [t1, t2] {
let (name, busy) = handle.join().unwrap();
println!("{name}: second lock is held by the other thread: {busy}");
}
}
t1: second lock is held by the other thread: true
t2: second lock is held by the other thread: true
- Verdict: stdlib.
std::sync::Mutexblocks inlock.try_lockreturnsErr(TryLockError::WouldBlock)at once when another thread holds the lock. - A deadlock is not undefined behaviour in Rust. The Rust Reference lists deadlocks among the behaviours that are not considered unsafe, so the compiler accepts code that deadlocks.
- A second
lockin the thread that holds the mutex does not return. The documentation leaves open whether it panics or deadlocks. - The guard unlocks the mutex when it goes out of scope. Here
_guardlives to the end of the closure, so each thread holds its first lock until both threads have tried.
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.thread
import kotlin.random.Random
class Account(var balance: Int) {
val lock = ReentrantLock()
}
fun transfer(from: Account, to: Account, amount: Int) {
while (true) {
from.lock.lock()
try {
if (to.lock.tryLock(1, TimeUnit.MILLISECONDS)) {
try {
from.balance -= amount
to.balance += amount
return
} finally {
to.lock.unlock()
}
}
} finally {
from.lock.unlock()
}
Thread.sleep(Random.nextLong(0, 2))
}
}
fun main() {
val a = Account(1000)
val b = Account(1000)
val workers = listOf(
thread { repeat(200) { transfer(a, b, 1) } },
thread { repeat(200) { transfer(b, a, 2) } },
)
workers.forEach { it.join() }
println("a: ${a.balance}, b: ${b.balance}, total: ${a.balance + b.balance}")
}
a: 1200, b: 800, total: 2000
- Verdict: stdlib. Kotlin on the JVM uses the JDK locks and threads.
kotlin.concurrent.threadstarts a thread. - The two threads lock in opposite orders, so a deadlock is possible. When
tryLockfails, the thread releases its first lock, sleeps for a random time, and starts again. This denies the no preemption condition. - The random sleep breaks the rhythm of the retries. Two threads that retry at the same time again and again would livelock.
$a = [object]::new()
$b = [object]::new()
$bothHold = [System.Threading.Barrier]::new(2)
$bothTried = [System.Threading.Barrier]::new(2)
$jobs = @(
@{ Name = 't1'; First = $a; Second = $b },
@{ Name = 't2'; First = $b; Second = $a }
)
$results = $jobs | ForEach-Object -ThrottleLimit 2 -Parallel {
$job = $_
$hold = $using:bothHold
$tried = $using:bothTried
[System.Threading.Monitor]::Enter($job.First)
try {
$hold.SignalAndWait()
$got = [System.Threading.Monitor]::TryEnter($job.Second, [timespan]::FromMilliseconds(200))
if ($got) { [System.Threading.Monitor]::Exit($job.Second) }
$tried.SignalAndWait()
}
finally {
[System.Threading.Monitor]::Exit($job.First)
}
"$($job.Name) got its second lock: $got"
}
$results | Sort-Object
t1 got its second lock: False
t2 got its second lock: False
- Verdict: stdlib.
ForEach-Object -Parallelruns each script block in its own runspace on its own thread. The scripts share .NET objects through$using:and the input objects, so .NET locks work across them. - PowerShell has no
lockstatement.[System.Threading.Monitor]::EnterandExitin atryandfinallydo the same work, andTryEnterwith a timeout gives the try-lock. - The output of parallel script blocks comes in the order they finish.
Sort-Objectmakes it the same on each run.
Variations and related ideas
- Self-deadlock. One thread is enough. A thread that holds a non-reentrant lock and asks for it again waits for itself. Python's
Lockblocks, and itsRLockcounts the acquisitions of the owner instead.2 A RustMutexleaves a relock in the same thread unspecified. The second call does not return, and it might panic or deadlock.9 POSIX gives a mutex type for each choice: aPTHREAD_MUTEX_NORMALrelock deadlocks,PTHREAD_MUTEX_ERRORCHECKreturnsEDEADLK, andPTHREAD_MUTEX_RECURSIVEcounts.7 Java monitors and C#lockare reentrant.1419 See the first pitfall. - Joins. A join is a wait for a thread to end, so it can be part of a cycle. A thread that joins itself waits forever. Python raises
RuntimeErrorinstead.20 POSIX letspthread_joinfail withEDEADLKwhen it detects a deadlock, and on Linux this includes a thread that names itself.2122 See Thread. - Channels. A send on an unbuffered channel succeeds only when a receiver is ready.23 A send with no receiver blocks forever, and two goroutines that each wait to receive from the other form a cycle. See Channel and the fourth pitfall.
- Async tasks. An async function that awaits a lock or a promise that another task holds can be part of a cycle. No thread blocks, so the program uses no CPU and shows no error. In Node.js, an ES module whose top-level
awaitnever settles exits with code 13.24 C# does not allowawaitin the body of alockstatement.19 See Async/await and the JavaScript example. - Livelock. The threads are not blocked, but they keep reacting to each other and do no useful work. The Java tutorial compares it to two people in a corridor who keep stepping into each other's way, each one trying to let the other pass.25 A random wait before each retry makes a repeat of the same collision less likely.
- Starvation. One thread cannot get access to a shared resource for a long time, because other threads take it again and again.25 The other threads make progress, so it is not a deadlock. A fair lock favours the thread that has waited longest. Java's
ReentrantLockwith fairness on guarantees the lack of starvation, at a cost in throughput.5 - Mutual exclusion in general. Locks, semaphores and monitors are the usual resources in a deadlock. See Mutual exclusion.
Pitfalls
Relock of a non-reentrant lock
A function that holds a lock calls a second function that takes the same lock. With Python's Lock, the second acquire waits for the thread itself.2 The timeout makes the program end.
This code runs but gives a wrong answer on purpose.
import threading
lock = threading.Lock()
items = []
def add_item(item):
# A plain "with lock:" here would wait forever.
if not lock.acquire(timeout=0.2):
print("add_item: timeout, the lock is held by this thread")
return
items.append(item)
lock.release()
def add_two(first, second):
with lock:
add_item(first)
add_item(second)
add_two("x", "y")
print("items:", items)
add_item: timeout, the lock is held by this thread
add_item: timeout, the lock is held by this thread
items: []
Each call of add_item times out, and no item is added. One fix is threading.RLock, which the owner can acquire again.2 A cleaner fix splits the code: a public function takes the lock, and a private function assumes that the caller holds it.
A thread that joins itself
A self-join waits for the end of the thread that waits. Python detects it.20
This code raises RuntimeError, on purpose.
import threading
threading.current_thread().join()
Python raises RuntimeError: cannot join current thread. The fix is to join each worker from the thread that started it. The C example shows pthread_join with the calling thread.
A lock held across a join
The main thread holds a lock and joins a worker. The worker needs the same lock to finish. Each one waits for the other: a cycle of a lock and a join.
This code runs but gives a wrong answer on purpose.
import threading
lock = threading.Lock()
done = []
def worker():
with lock:
done.append("worker")
with lock:
t = threading.Thread(target=worker)
t.start()
t.join(timeout=0.2)
print("worker still running:", t.is_alive())
t.join()
print("after release:", done)
worker still running: True
after release: ['worker']
The timeout lets the program continue. Without it, the program would stop at the first join. The fix is to release the lock before the join. Callbacks, joins and calls to code that you do not control are all dangerous while you hold a lock.
A send on an unbuffered channel with no receiver
An unbuffered channel needs a sender and a receiver at the same time.23 Here the only goroutine sends, so no receiver ever comes.
This code fails on purpose. The output below is the error.
package main
import "fmt"
func main() {
ch := make(chan int)
ch <- 1
fmt.Println(<-ch)
}
No goroutine can run, so the Go runtime stops the program with fatal error: all goroutines are asleep - deadlock! and exit code 2.15 The fix is a receiver in another goroutine, or a buffer: make(chan int, 1).
Cost
- Lock ordering costs almost nothing at run time: a comparison of two keys. The cost is in the design. Every lock needs a place in the order, and the code must know the second lock before it takes the first one.
- All at once.
std::lockmust find an order that does not deadlock, and the standard leaves the method to the implementation.3 Measure it on a hot path. A task that takes all its resources at the start can keep some of them unused for a long time.1 - Try, back off and retry wastes the work that the failed attempt did. Under heavy contention the retries can repeat, which is a livelock. The code must also handle the failure path, which is a source of bugs.
- Timeouts turn a hang into an error. The program still has to decide what to do: retry, report or abort. A short timeout can fail under normal load. A long one makes a real deadlock slow to see.
- Detection has a run time cost. The Java documentation warns that
findDeadlockedThreadsmight be expensive.12 PostgreSQL waits fordeadlock_timeoutbefore it checks, because the check is relatively expensive.17 Recovery throws away the work of the aborted task, so the program must be able to retry it.16 - Avoidance checks the safety of the state at each request, and it needs the maximum needs of each task in advance.1
History
- 1968. Dijkstra's "Cooperating Sequential Processes" (EWD 123) was published in Programming Languages, edited by F. Genuys. Its section 6 is "The Problem of the Deadly Embrace", and section 6.1 is "The Banker's Algorithm".10
- 1968. J. W. Havender described in the IBM Systems Journal how OS/360 avoids some deadlocks. The system took the resources for each job step in a fixed order.1
- 1971. E. G. Coffman Jr., M. J. Elphick and A. Shoshani published "System Deadlocks" in ACM Computing Surveys. It states the four conditions and sorts the treatments into prevention, detection and recovery, and avoidance.1
- 1977. Dijkstra wrote "The mathematics behind the Banker's Algorithm" (EWD 623).11
References
- E. G. Coffman Jr., M. J. Elphick and A. Shoshani, System Deadlocks, ACM Computing Surveys 3(2), 1971, pp. 67 to 78, 1 Introduction; 2 Characterizations of Deadlocks; 3 Prevention of Deadlock; 4 Deadlock Detection and Recovery; 5 Avoiding Deadlocks Using Information on Resource Requirements; reference 4 (Havender)
- Python 3.14 documentation, threading, Lock objects, acquire with blocking and timeout; RLock objects
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.lock.algorithm], paragraph 5
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.lock.scoped], paragraph 2
- Java SE 25 API, Class ReentrantLock, class description (fairness); tryLock(long, TimeUnit)
- .NET API reference, Monitor.TryEnter, TryEnter(Object, TimeSpan), Returns
- POSIX.1-2024, pthread_mutex_lock, DESCRIPTION (the table of mutex types); RETURN VALUE; ERRORS
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.timedmutex.requirements.general], paragraphs 4 and 7
- Rust standard library, Struct Mutex, lock, the paragraph on a lock in a thread that already holds it; try_lock, Errors
- Edsger W. Dijkstra, Cooperating Sequential Processes (EWD 123), in F. Genuys (ed.), Programming Languages, Academic Press, 1968, table of contents, 6 The Problem of the Deadly Embrace; 6.1 The Banker's Algorithm
- Edsger W. Dijkstra, The mathematics behind the Banker's Algorithm (EWD 623), 1977, the whole note
- Java SE 25 API, Interface ThreadMXBean, findDeadlockedThreads()
- Java SE 25 tool specifications, The jstack Command, Description; Options, -l
- The Java Language Specification, Java SE 25 Edition, 17.1 Synchronization
- Go runtime source, src/runtime/proc.go at go1.27.3, checkdead, lines 6414 to 6519
- PostgreSQL 18 documentation, Explicit Locking, 13.3.4 Deadlocks
- PostgreSQL 18 documentation, Lock Management, deadlock_timeout
- The Rust Reference, Behavior not considered unsafe, Deadlocks
- C# language reference, The lock statement, the remarks on reentry, on await in a lock body, and Guidelines
- Python 3.14 documentation, threading, Thread objects, join
- POSIX.1-2024, pthread_join, ERRORS, EDEADLK
- Linux manual page, pthread_join(3), ERRORS, EDEADLK
- The Go Programming Language Specification, language version go1.27, Channel types
- Node.js documentation, Process, Exit codes, 13 Unsettled Top-Level Await
- The Java Tutorials, Starvation and Livelock, Starvation; Livelock
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag YJ5FP2 Edit this page History Report an error Markdown