ENع
→Deadlock conditions
الدرس 24 · Deadlock

The four conditions for deadlock

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 24 · تفاعلي
01 / 10

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;
}
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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;
    }
  2. 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 1
  3. T2 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.
  4. 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."
  5. 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: False
  6. 1. 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: T2
  7. 2. 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.
  8. 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.
  9. 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            yes
  10. Break 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

اختبار يتاح بعد الخطوة الأخيرة.