ENع
→Lock ordering
الدرس 26 · Deadlock

Preventing deadlock with lock ordering

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

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

Two threads each need the same two locks. If they take them in opposite orders, one badly timed switch leaves each thread holding the lock the other wants, and both wait forever. Watch that circle form, then fix it with one rule: number every lock and always take locks in rising order. The lesson The four conditions for deadlock names the conditions this rule breaks, Resource allocation graphs draws the circle, and Locks, spinlocks and atomic instructions explains the locks themselves.

ستتعلّم

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

شكل 26 · تفاعلي
01 / 12

Two threads, two locks

Two threads share two locks, A and B. A lock is like a key only one thread can hold; any other thread that asks for it must wait. Each thread needs both keys to do its work, but they ask in opposite orders.

A = threading.Lock()      B = threading.Lock()

thread 1                  thread 2
with A:                   with B:
    with B:                   with A:
        work()                    work()

with X:   take lock X (wait while another thread holds it),
          release it when the block ends
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Two threads, two locks

    Two threads share two locks, A and B. A lock is like a key only one thread can hold; any other thread that asks for it must wait. Each thread needs both keys to do its work, but they ask in opposite orders.

    A = threading.Lock()      B = threading.Lock()
    
    thread 1                  thread 2
    with A:                   with B:
        with B:                   with A:
            work()                    work()
    
    with X:   take lock X (wait while another thread holds it),
              release it when the block ends
  2. Thread 1 takes A

    Thread 1 runs its first line, with A:. Lock A is free, so Thread 1 takes it and carries on. In Python, with takes the lock when the block starts and releases it when the block ends.

    thread 1   with A:      A is free -> taken
    
    lock   holder
    A      thread 1
    B      -
  3. Thread 2 takes B

    The scheduler switches threads. Thread 2 runs its first line, with B:. Lock B is free too, so Thread 2 takes it. Each thread now holds one key.

    switch to thread 2
    thread 2   with B:      B is free -> taken
    
    lock   holder
    A      thread 1
    B      thread 2
  4. Thread 1 must wait

    Thread 1's second line asks for B. Thread 2 holds B, so Thread 1 blocks: it sleeps until B is released. It keeps holding A while it waits.

    switch to thread 1
    thread 1   with B:      B is held by thread 2 -> blocked
    
    thread 1   holds A, waits for B (held by thread 2)
  5. Thread 2 must wait

    Thread 2's second line asks for A. Thread 1 holds A, so Thread 2 blocks too, still holding B. Each thread now waits for a key the other one holds.

    switch to thread 2
    thread 2   with A:      A is held by thread 1 -> blocked
    
    thread 1   holds A, waits for B (held by thread 2)
    thread 2   holds B, waits for A (held by thread 1)
  6. A circle: deadlock

    Thread 1 waits for Thread 2, and Thread 2 waits for Thread 1: a circle. Neither can ever go on. All four conditions hold: mutual exclusion, hold and wait, no preemption and circular wait. Break any one and deadlock cannot happen.

    wait-for circle:  thread 1 -> thread 2 -> thread 1
    
    mutual exclusion  one holder per lock            yes
    hold and wait     each holds one, waits for one  yes
    no preemption     nobody can take a lock away    yes
    circular wait     the circle above               yes
    
    every reachable state of this pair of programs: 13
    of those, deadlocked: 1 (the one shown)
  7. The rule: one order

    Start again with one rule. Number every lock, A is 1 and B is 2, and always take locks in rising order. Thread 2's code is rewritten to take A first, then B. Thread 1 already follows the rule.

    rank   A = 1   B = 2
    rule   hold lock n -> only ask for locks above n
    
    thread 1 (unchanged)      thread 2 (rewritten)
    with A:                   with A:
        with B:                   with B:
            work()                    work()
    
    the same rule in C (C99, POSIX threads):
    
    #define _POSIX_C_SOURCE 200809L
    #include <pthread.h>
    #include <stdio.h>
    
    static pthread_mutex_t lock[2] = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER };
    static int balance[2] = { 100, 100 };
    
    /* move money; always lock the lower-numbered account first */
    static void transfer(int from, int to) {
        int lo = from < to ? from : to, hi = from < to ? to : from;
        pthread_mutex_lock(&lock[lo]);
        pthread_mutex_lock(&lock[hi]);
        balance[from] -= 1;
        balance[to] += 1;
        pthread_mutex_unlock(&lock[hi]);
        pthread_mutex_unlock(&lock[lo]);
    }
    
    static void *t1(void *arg) { (void)arg; for (int i = 0; i < 100000; i++) transfer(0, 1); return NULL; }
    static void *t2(void *arg) { (void)arg; for (int i = 0; i < 100000; i++) transfer(1, 0); return NULL; }
    
    int main(void) {
        pthread_t a, b;
        pthread_create(&a, NULL, t1, NULL);
        pthread_create(&b, NULL, t2, NULL);
        pthread_join(a, NULL);
        pthread_join(b, NULL);
        printf("%d %d\n", balance[0], balance[1]);
        return 0;
    }
    
    prints   100 100
  8. Thread 1 takes A again

    Same timing as before. Thread 1 runs with A: and takes lock A, which is free.

    thread 1   with A:      A is free -> taken
    
    lock   holder
    A      thread 1
    B      -
  9. Thread 2 waits, holding nothing

    The scheduler switches. Thread 2 now asks for A first, and Thread 1 holds it, so Thread 2 blocks. But it blocks holding nothing, so lock B stays free for Thread 1.

    switch to thread 2
    thread 2   with A:      A is held by thread 1 -> blocked
    
    thread 2   holds nothing, waits for A
    lock B     free
  10. Thread 1 finishes

    Thread 1 takes B, which is free, does its work, then leaves both with blocks, releasing B and then A. Thread 2 was waiting for A, so it can run again.

    switch to thread 1
    thread 1   with B:      B is free -> taken
    thread 1   work()
    thread 1   end of blocks: release B, release A
    thread 2   A is free: no longer blocked
  11. Thread 2 finishes

    Thread 2 takes A, then B, does its work and releases both. Both threads are done. Thread 2 waited a little while, but nobody waited forever.

    thread 2   with A:      taken
    thread 2   with B:      taken
    thread 2   work()
    thread 2   release B, release A
    
    both threads finished
  12. Why no circle can form

    A thread holding lock n only ever waits for a lock numbered above n. A circle of waits would have to come back down to n, which the rule forbids. That breaks circular wait. Linux keeps a lock order, and its lockdep tool checks it.

    every schedule, checked exhaustively by the model:
      opposite orders (A,B / B,A)  13 states, 1 deadlock
      one order      (A,B / A,B)  12 states, 0 deadlocks
    
    the same check as a Python simulation:
    
    def run(order1, order2, turns):
        code = {1: order1, 2: order2}
        held = {}                       # lock -> thread holding it
        got = {1: 0, 2: 0}              # locks each thread has taken
        for t in turns:                 # the scheduler picks who runs
            if got[t] == 2:
                continue                # finished
            want = code[t][got[t]]
            if want in held:
                continue                # held by the other: wait
            held[want] = t
            got[t] += 1
            if got[t] == 2:             # has both: work, then release
                for lock in code[t]:
                    del held[lock]
        stuck = [t for t in (1, 2) if got[t] < 2]
        return "deadlock" if stuck else "both finished"
    
    turns = [1, 2, 1, 2, 1, 2]
    print(run("AB", "BA", turns))      # opposite orders
    print(run("AB", "AB", turns))      # one order
    
    prints:
    deadlock
    both finished

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