The four conditions for deadlock
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Two threads, two locks, and code that looks perfectly reasonable: one thread takes A then B, the other takes B then A. With unlucky timing each ends up holding one lock and sleeping until the other lets go, and neither ever does. That is deadlock. Watch it happen step by step, then see the four conditions that must all be true for it to happen: mutual exclusion, hold and wait, no preemption and circular wait. Break any one and the deadlock cannot form. This builds on the Synchronisation lessons Locks, spinlocks and atomic instructions and Producer-consumer, readers-writers and dining philosophers.
Two threads, two locks
Two threads run at the same time and share two locks, A and B. A lock lets only one thread at a time use something shared. T1 takes A, then B. T2 takes the same locks in the other order: B, then A.
thread T1 thread T2
1 lock(A); 1 lock(B);
2 lock(B); 2 lock(A);
3 work(); 3 work();
lock(X) take lock X; if another thread holds it,
sleep until it is released
work() use A and B, then release both
the same program in C99 with POSIX threads:
#define _POSIX_C_SOURCE 200809L
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER;
void *t1(void *arg) {
(void)arg;
pthread_mutex_lock(&A);
sleep(1); /* let the other thread take its first lock */
pthread_mutex_lock(&B); /* blocks until B is unlocked */
puts("T1 done");
pthread_mutex_unlock(&B);
pthread_mutex_unlock(&A);
return NULL;
}
void *t2(void *arg) {
(void)arg;
pthread_mutex_lock(&B);
sleep(1); /* let the other thread take its first lock */
pthread_mutex_lock(&A); /* blocks until A is unlocked */
puts("T2 done");
pthread_mutex_unlock(&A);
pthread_mutex_unlock(&B);
return NULL;
}
int main(void) {
pthread_t x, y;
pthread_create(&x, NULL, t1, NULL);
pthread_create(&y, NULL, t2, NULL);
pthread_join(x, NULL);
pthread_join(y, NULL);
puts("both done");
return 0;
}اقرأ الدرس خطوة بخطوة
Two threads, two locks
Two threads run at the same time and share two locks, A and B. A lock lets only one thread at a time use something shared. T1 takes A, then B. T2 takes the same locks in the other order: B, then A.
thread T1 thread T2 1 lock(A); 1 lock(B); 2 lock(B); 2 lock(A); 3 work(); 3 work(); lock(X) take lock X; if another thread holds it, sleep until it is released work() use A and B, then release both the same program in C99 with POSIX threads: #define _POSIX_C_SOURCE 200809L #include <pthread.h> #include <stdio.h> #include <unistd.h> pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER; void *t1(void *arg) { (void)arg; pthread_mutex_lock(&A); sleep(1); /* let the other thread take its first lock */ pthread_mutex_lock(&B); /* blocks until B is unlocked */ puts("T1 done"); pthread_mutex_unlock(&B); pthread_mutex_unlock(&A); return NULL; } void *t2(void *arg) { (void)arg; pthread_mutex_lock(&B); sleep(1); /* let the other thread take its first lock */ pthread_mutex_lock(&A); /* blocks until A is unlocked */ puts("T2 done"); pthread_mutex_unlock(&A); pthread_mutex_unlock(&B); return NULL; } int main(void) { pthread_t x, y; pthread_create(&x, NULL, t1, NULL); pthread_create(&y, NULL, t2, NULL); pthread_join(x, NULL); pthread_join(y, NULL); puts("both done"); return 0; }T1 takes lock A
T1 runs line 1, lock(A). Lock A is free, so T1 gets it at once: A's key moves onto T1's card. While T1 holds A, any other thread that asks for A must wait.
event T1 takes A lock A held by T1 lock B free T1 at line 2 T2 at line 1T2 takes lock B
Before T1 reaches line 2, the scheduler switches to T2. T2 runs lock(B). B is free too, so T2 gets it. Each thread holds one lock and nobody waits yet. But each one's next line asks for the lock the other holds.
a context switch: the scheduler pauses T1 and runs T2 event T2 takes B lock A held by T1 lock B held by T2 this is the unlucky timing. If T1 had run both lines first, there would be no problem this time. now it is too late: each next line wants a held lock, so whatever runs next, deadlock is certain.T1 asks for B and waits
T1 runs line 2, lock(B). But B's key is on T2's card. T1 cannot go on, so the operating system puts it to sleep until B is released. T1 keeps holding A while it sleeps.
event T1 waits for B T1 holds A, asleep, waiting for B T2 holds B, still awake; its next line is lock(A) pthread_mutex_lock(3p): "If the mutex is already locked by another thread, the calling thread shall block until the mutex becomes available."T2 asks for A: deadlock
T2 runs lock(A). A is held by T1, which is asleep waiting for B. So T2 sleeps too. Each waits for a lock the other holds, and neither can ever release one. This is deadlock: both wait forever.
event T2 waits for A T1 holds A, waits for B (held by T2) T2 holds B, waits for A (held by T1) runnable none finished none the same deadlock in Python (the timeout only lets the demo end; a plain lock() would wait forever): import threading A, B = threading.Lock(), threading.Lock() both = threading.Barrier(2) got = {} def thread(name, first, second): with first: # line 1: take the first lock both.wait() # each now holds one lock got[name] = second.acquire(timeout=0.5) # line 2 both.wait() # neither lets go early t1 = threading.Thread(target=thread, args=("T1", A, B)) t2 = threading.Thread(target=thread, args=("T2", B, A)) t1.start(); t2.start(); t1.join(); t2.join() print("T1 got B:", got["T1"]) print("T2 got A:", got["T2"]) prints: T1 got B: False T2 got A: False1. Mutual exclusion
Why did it happen? Four conditions were all true at once. First, mutual exclusion: a lock has only one holder at a time. T2 could not share A with T1, so it had to wait.
the four conditions (Coffman, Elphick and Shoshani, 1971): 1 Mutual exclusion a lock has at most one holder at a time 2 Hold and wait a thread keeps the locks it has while it waits for another 3 No preemption only the holder can release a lock; nothing takes it away 4 Circular wait the waits form a loop: T1 waits for T2, T2 waits for T1 deadlock needs all four at once. 1 mutual exclusion here: lock A one holder: T1 lock B one holder: T22. Hold and wait
Second, hold and wait: each thread kept the lock it already had while it waited for another one. T1 holds A and waits for B. T2 holds B and waits for A.
2 hold and wait here: T1 holds A waits for B T2 holds B waits for A a thread that held nothing while it waited could not block anyone else.3. No preemption
Third, no preemption: nothing can take a lock away from its holder. Only T1 will release A, and T1 is asleep. The operating system will not pull A off T1 and hand it to T2. The same goes for B.
3 no preemption here: lock A stays with T1 until T1 unlocks it lock B stays with T2 until T2 unlocks it the OS cannot safely take a lock back: the holder may be halfway through changing the shared data.4. Circular wait
Fourth, circular wait: the waiting closes a loop. T1 waits for B, which T2 holds. T2 waits for A, which T1 holds. Follow the arrows from T1 and you come back to T1.
4 circular wait here: T1 -> waits for B -> held by T2 T2 -> waits for A -> held by T1 wait-for graph T1 -> T2, T2 -> T1 cycle yesBreak one, no deadlock
Break any one condition and this deadlock cannot happen. Here T2 takes A first, like T1. T2 waits for A while holding nothing, T1 finishes and releases both, then T2 gets A and B. No loop forms.
fix: every thread takes A before B (one lock order) thread T1 thread T2 1 lock(A); 1 lock(A); 2 lock(B); 2 lock(B); 3 work(); 3 work(); T1 takes A T2 waits for A T1 takes B T1 works, releases its locks T2 takes A T2 takes B every interleaving, opposite orders: 2 of 4 deadlock every interleaving, one order: 0 of 2 deadlock
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01T1 runs lock(A); lock(B); and T2 runs lock(B); lock(A);. Which timing leads to deadlock?
Once each thread holds its first lock, each one's next line asks for the lock the other holds, so both sleep for ever. If one thread runs both lines first, it finishes and releases both locks, and the other then proceeds. Deadlock here depends on timing.
02Which of these is NOT one of the four conditions for deadlock?
The four conditions are mutual exclusion, hold and wait, no preemption and circular wait. Starvation (a thread waiting a very long time while others keep going) is a different problem: it can end, a deadlock cannot.
03In the stuck state, which condition does 'T1 holds A and waits for B; T2 holds B and waits for A' describe on its own?
Hold and wait means a thread keeps the resources it already has while it waits for more. Both threads do that here. Together with the loop it forms (circular wait) and the other two conditions, the threads are stuck.
04What does 'no preemption' mean for locks?
A held lock stays with its holder until the holder unlocks it. The system cannot safely take it back, because the holder may be halfway through changing the data the lock protects.
05Both threads are changed to take A before B. Why can they no longer deadlock?
With one order, any thread holding B already holds A, so no thread holding B can ever be waiting for A. The loop T1 -> B -> T2 -> A -> T1 cannot close, so circular wait is broken. Breaking any one of the four conditions is enough.
المسرد
- Deadlock
- A state in which a set of threads each wait for something held by another thread in the set, so none of them can ever continue.
- Lock (mutex)
- A tool that lets only one thread at a time run a piece of code or use some shared data. A thread takes it with lock() and gives it back with unlock().
- Mutual exclusion
- A resource can be used by only one thread at a time; a lock has at most one holder.
- Hold and wait
- A thread keeps the resources it already holds while it waits to get more.
- No preemption
- A resource cannot be taken away from the thread that holds it; the holder releases it only when it chooses to.
- Circular wait
- A loop of waiting threads: T1 waits for something T2 holds, T2 for something T3 holds, and so on, until the last waits for something T1 holds.
- Lock ordering
- A rule that every thread takes locks in the same fixed order (for example A before B). It breaks circular wait, so it prevents deadlock.
الملاحظات والمصادر
- On the cards, lock(A) is short for pthread_mutex_lock(&A) in C, or A.acquire() in Python. The full C program is in the first step: compiled and run, it usually hangs for ever, because each thread sleeps for one second after its first lock.
- Deadlock depends on timing. With these two orders, some interleavings finish and some get stuck, so the bug can hide in testing and appear only now and then.
- The four conditions come from Coffman, Elphick and Shoshani, "System Deadlocks" (ACM Computing Surveys, 1971). They are necessary: if any one is missing, deadlock cannot occur.
- No preemption is about the system: neither the operating system nor the lock library takes a held lock away. (A Python Lock may be released by a thread that does not own it, but nothing does that for you.)
- The loop on the table is a wait-for graph: an arrow from each waiting thread to the lock it wants, and from each lock to its holder. The next lesson, Resource allocation graphs, draws it properly.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 32: Common Concurrency Problems (deadlock)
- Berkeley CS162, Lecture 13: Scheduling 4 and Deadlock (four requirements for deadlock)
- MIT 6.1810 (2024), lecture notes: Locking (lock ordering and deadlock)
- Linux kernel documentation: Runtime locking correctness validator (lock inversion deadlock)
- POSIX / Linux man-pages: pthread_mutex_lock(3p)
- Python documentation: threading (Lock and Barrier)
اختبار يتاح بعد الخطوة الأخيرة.