ENع
←Deadlock recovery
Lesson 28 · Deadlock

Detecting and recovering from deadlock

14 min11 steps5 questionsIntermediate
About this lesson

Preventing deadlock costs care, and avoiding it costs knowing every request in advance. The third way is to let deadlock happen, then find it and break it. Watch three threads and three locks jam into a circle, a detector build the wait-for graph and follow its arrows round the cycle, and a victim be aborted so the others can finish. Then see the Linux kernel do the same for file locks with EDEADLK. It builds on The four conditions for deadlock, Resource allocation graphs and Avoiding deadlock: the banker's algorithm.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 28 · Interactive
01 / 11

Each thread takes one lock

Three threads each need two locks: T1 needs A then B, T2 needs B then C, T3 needs C then A. Each grabs its first lock. An arrow from a lock to a thread means that thread holds it.

T1:  lock(A); lock(B);  work  unlock both
T2:  lock(B); lock(C);  work  unlock both
T3:  lock(C); lock(A);  work  unlock both

all three run at the same time and get their first lock:
  A held by T1    B held by T2    C held by T3

lock   ->  thread    "held by"
Loading figure…
or ← →
Read the lesson step by step
  1. Each thread takes one lock

    Three threads each need two locks: T1 needs A then B, T2 needs B then C, T3 needs C then A. Each grabs its first lock. An arrow from a lock to a thread means that thread holds it.

    T1:  lock(A); lock(B);  work  unlock both
    T2:  lock(B); lock(C);  work  unlock both
    T3:  lock(C); lock(A);  work  unlock both
    
    all three run at the same time and get their first lock:
      A held by T1    B held by T2    C held by T3
    
    lock   ->  thread    "held by"
  2. Everyone waits forever

    Each thread now asks for its second lock, and another thread holds it. T1 waits for T2, T2 for T3, T3 for T1. A thread asleep in lock() cannot release anything, so none of them ever wakes. This is deadlock.

    T1 asks for B   (T2 holds it)   T1 sleeps
    T2 asks for C   (T3 holds it)   T2 sleeps
    T3 asks for A   (T1 holds it)   T3 sleeps
    
    thread ->  lock      "waits for"
    
    all four conditions hold:
      mutual exclusion · hold-and-wait · no preemption · circular wait
    nothing inside the three threads can end this
  3. The detector builds a graph

    So a detector outside the threads checks. It runs every so often, or when a lock has been waited on too long. It builds the wait-for graph: each waiting thread points to the thread holding the lock it wants.

    line 1   g = waits_for()
    
    T1 wants B, B is held by T2   ->  T1 waits for T2
    T2 wants C, C is held by T3   ->  T2 waits for T3
    T3 wants A, A is held by T1   ->  T3 waits for T1
    
    wait-for graph   {"T1":"T2","T2":"T3","T3":"T1"}
    
    it is the resource allocation graph with the lock nodes taken out
  4. Follow the arrows: a cycle

    Now it follows the arrows from T1: T1 waits for T2, T2 for T3, T3 for T1. It is back where it started, so there is a cycle. When each lock has only one copy, a cycle means deadlock.

    line 2   loop = find_cycle(g)
    
    start at T1 and follow the arrows:
      T1 -> T2 -> T3 -> T1   back at T1
    cycle   [T1, T2, T3]
    
    one copy of each lock:   cycle  <=>  deadlock
    every thread on the cycle is stuck
  5. When resources have many copies

    If a resource has several copies, a cycle is not enough proof. The detector asks instead: with the free copies, can some thread finish? It pretends that thread returns what it holds, and repeats. Threads that never finish are deadlocked.

    Avail = free copies     Alloc[t] = held     Request[t] = asked for
    
    UNFINISHED = every thread
    repeat:  if Request[t] <= Avail:
                 Avail += Alloc[t];  t can finish
    left in UNFINISHED  ->  deadlocked
    
    example: R1 has 2 copies, R2 has 1
      T1 holds R1, asks R2   T2 holds R1   T3 holds R2, asks R1
      finish order T2, T3, T1: a cycle, but no deadlock
    our locks: nobody can finish, deadlocked T1, T2, T3
  6. Pick a victim

    To break the cycle, one thread must lose. The detector picks the cheapest to undo: least work done, fewest locks held or lowest priority. In this example T3 has done 1 second of work; T1 and T2 have done 5 and 4.

    line 3   abort(cheapest(loop))
    
    work done so far   T1 5 s   T2 4 s   T3 1 s   (example numbers)
    cheapest(["T1","T2","T3"])  ->  T3
    
    other costs a real system weighs:
      locks held · priority · how often it was the victim before
  7. Abort the victim

    T3 is aborted: killed, or rolled back to a saved checkpoint so its half-done changes are undone. Either way it lets go of lock C. Its arrows vanish and the cycle is broken.

    recover by:
      terminate   kill T3; it gives up every lock it holds
      roll back   undo T3 to a checkpoint (databases: abort the transaction)
      preempt     take C away from T3 for a while
    
    lock C is free
    wait-for graph now: T1 -> T2 only, no cycle
  8. T2 gets C and finishes

    Lock C is free, so T2, which was waiting for it, gets it. Holding B and C, T2 does its work, finishes and releases both locks.

    C  -> T2        T2 wakes up
    T2 holds B and C: does its work
    T2 unlocks B and C
    
    B is free now
  9. T1 finishes, T3 starts over

    B is free, so T1 gets it and finishes too. T3 starts again from the beginning. Its lost work is the price of recovery, and if the same timing happens again, it can deadlock again.

    B  -> T1        T1 wakes up, works, unlocks A and B
    T3 restarts:    lock(C); lock(A); ...
    
    lost: T3's 1 s of work
    restarting in exactly the same way may deadlock again
    
    the whole run as a Python simulation:
    
    holds = {"A": "T1", "B": "T2", "C": "T3"}   # lock -> owner
    wants = {"T1": "B", "T2": "C", "T3": "A"}   # thread -> lock it waits for
    work = {"T1": 5, "T2": 4, "T3": 1}            # seconds of work done so far
    
    def waits_for():                # thread -> the thread it waits for
        return {t: holds[l] for t, l in wants.items() if l in holds}
    
    def find_cycle(g):
        for start in g:
            path, t = [], start
            while t in g and t not in path:
                path.append(t)
                t = g[t]
            if t in path:           # back at a thread already on the path
                return path[path.index(t):]
        return None
    
    def cheapest(loop):             # the least work lost if we undo it
        return min(loop, key=lambda t: work[t])
    
    def abort(t):
        print("abort", t)
        for lock in [l for l, owner in holds.items() if owner == t]:
            del holds[lock]         # its locks are free again
        wants.pop(t, None)
    
    def detector():
        g = waits_for()
        loop = find_cycle(g)
        print("cycle:", " -> ".join(loop + loop[:1]))
        abort(cheapest(loop))
    
    detector()
    running = ["T1", "T2"]
    while running:
        for t in list(running):
            lock = wants.get(t)
            if lock in holds:       # still waiting
                continue
            if lock:
                holds[lock] = t
                del wants[t]
                print(t, "gets", lock)
            print(t, "finishes")
            for l in [l for l, owner in holds.items() if owner == t]:
                del holds[l]
            running.remove(t)
    print("T3 restarts")
    
    prints:
    cycle: T1 -> T2 -> T3 -> T1
    abort T3
    T2 gets C
    T2 finishes
    T1 gets B
    T1 finishes
    T3 restarts
  10. A kernel that does this

    Linux does this for file locks. If an fcntl F_SETLKW request would make processes wait in a circle, the kernel fails one request with EDEADLK. That process is the victim: it gives up its own lock and the other goes ahead.

    two processes, two bytes of one file as locks A and B (C99 + POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <errno.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <sys/wait.h>
    #include <unistd.h>
    
    /* lock one byte of the file: byte 0 is lock A, byte 1 is lock B */
    static int lock_byte(int fd, off_t byte) {
        struct flock fl = { 0 };
        fl.l_type = F_WRLCK;
        fl.l_whence = SEEK_SET;
        fl.l_start = byte;
        fl.l_len = 1;
        return fcntl(fd, F_SETLKW, &fl);   /* W: wait until granted */
    }
    
    int main(void) {
        int fd = open("locks.dat", O_RDWR | O_CREAT, 0600);
        int p[2];
        char c;
        if (fd < 0 || pipe(p) != 0) return 1;
        lock_byte(fd, 0);                  /* parent holds A */
        pid_t pid = fork();
        if (pid == 0) {                    /* child */
            lock_byte(fd, 1);              /* child holds B */
            if (write(p[1], "x", 1) != 1) _exit(1);
            sleep(1);                      /* let the parent block on B */
            if (lock_byte(fd, 0) == -1 && errno == EDEADLK) {
                printf("child: EDEADLK, giving up B\n");
                fflush(stdout);
                _exit(0);                  /* exiting releases B */
            }
            _exit(1);
        }
        if (read(p[0], &c, 1) != 1) return 1;   /* child holds B now */
        lock_byte(fd, 1);                  /* parent waits for B */
        printf("parent: got A and B\n");
        waitpid(pid, NULL, 0);
        unlink("locks.dat");
        return 0;
    }
    
    prints:
    child: EDEADLK, giving up B
    parent: got A and B
  11. Detect, then recover

    Detection lets deadlock happen, then finds it: build the wait-for graph and look for a cycle. Recovery breaks the cycle by aborting or rolling back a victim. It suits rare deadlocks; a fixed lock order prevents them more simply.

    prevent    break one of the four conditions (lock ordering)
    avoid      refuse unsafe requests (the banker's algorithm)
    detect     let it happen, find the cycle
    recover    abort, roll back or preempt a victim
    ignore     restart by hand if it is rare enough
    
    used by: databases (abort a transaction), Linux file locks (EDEADLK)
    Linux lockdep warns about wrong lock orders before they deadlock

Quiz Unlocks after the last step.