Detecting and recovering from deadlock
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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"
اقرأ الدرس خطوة بخطوة
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"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 thisThe 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 outFollow 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 stuckWhen 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, T3Pick 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 beforeAbort 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 cycleT2 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 nowT1 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 restartsA 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 BDetect, 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
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01T1 waits for a lock held by T2, T2 waits for a lock held by T3, and T3 waits for a lock held by T1. Each lock has one copy. What does the detector conclude?
Following the arrows T1 → T2 → T3 → T1 comes back to the start. With one copy of each lock, a cycle means every thread on it waits forever.
02Why is a cycle not enough proof of deadlock when a resource has several copies?
With copies, a waiting thread can be served by any copy, including one held by a thread that is not stuck. The matrix check asks whether every thread can still finish, given the free copies.
03How does a detector usually pick the victim?
Recovery throws work away, so systems pick the victim that loses the least: little work done, few locks held, low priority, and not one that was already the victim many times.
04Why do databases roll a victim back instead of simply killing it?
A lock usually protects data being updated. Aborting the transaction undoes its partial changes, so the data is consistent when the locks pass to the other threads.
05Two processes each hold a byte lock from fcntl and then each asks for the other's byte with F_SETLKW. What does Linux do?
For F_SETLKW the kernel looks for a cycle of waiting processes and makes one blocking request fail with EDEADLK. The search is only 10 steps deep, and the man page warns of both missed deadlocks and false alarms.
المسرد
- Deadlock
- A set of threads where each one waits for something another one in the set holds, so none of them can ever continue.
- Wait-for graph
- A graph with one node per thread and an arrow from each waiting thread to the thread that holds what it wants. It is the resource allocation graph with the resource nodes removed.
- Cycle
- A path of arrows that comes back to where it started. With one copy of each resource, a cycle in the wait-for graph is a deadlock.
- Deadlock detector
- Code that runs now and then (or when a wait is too long), builds the graph or the matrices, and reports which threads are deadlocked.
- Victim
- The thread or process chosen to lose its resources so that a deadlock can be broken, usually the one that is cheapest to undo.
- Rollback
- Undoing a victim's work back to a saved point, such as aborting a database transaction, so its half-done changes disappear.
- EDEADLK
- The error code Linux returns from fcntl F_SETLKW when granting the wait would create a deadlock between processes.
الملاحظات والمصادر
- The wait-for graph is the resource allocation graph with the lock nodes removed: an arrow T1 → T2 means T1 waits for a lock that T2 holds. With one copy of each lock, a cycle in it is exactly a deadlock.
- With several copies of a resource a cycle is necessary but not enough. The detector then runs a matrix check much like the banker's safety check, but on what threads have asked for now, not on their maximum claims.
- The work numbers (T1 5 s, T2 4 s, T3 1 s) are made up for the example; real systems weigh work lost, locks held, priority and how often a thread was already the victim.
- Killing a thread that holds a lock can leave the data that lock protects half-changed. That is why databases roll the victim back (abort the transaction) rather than just stop it.
- Linux checks for cycles among processes waiting on fcntl record locks, but only 10 steps deep, and its man page warns of both missed deadlocks and false EDEADLK errors.
- Most general-purpose kernels do not run a detector over ordinary thread locks. In the kernel itself, Linux's lockdep checks lock order while it runs and reports orders that could deadlock, even ones that never did.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 32: Common Concurrency Problems (Detect and Recover)
- Berkeley CS162 Fall 2026, Lecture 13: Scheduling 4, Deadlock (detection algorithm and recovery)
- MIT 6.1810 (2024), lecture notes: Locking (deadlock and lock order)
- Linux man-pages: F_SETLKW(2const), record locks and EDEADLK
- Linux man-pages: fcntl(2)
- Linux kernel documentation: Runtime locking correctness validator (lockdep)
اختبار يتاح بعد الخطوة الأخيرة.