Section 9.15

Lock ordering

Definition

Lock ordering, also called a lock hierarchy, is a rule that prevents deadlock §9.14, a state in which threads wait for each other forever, among a program’s locks, objects that one thread at a time may hold. Every lock gets a fixed place in one order, usually written as a number called its rank. A thread that holds a lock may wait for another lock only if that lock comes later in the order. Then no cycle of threads, each waiting for a lock the next one holds, can form.

The idea

Two threads that need the same two locks deadlock if they take them in opposite orders: A holds X and waits for Y, while B holds Y and waits for X. The fix is not cleverness at run time but one direction agreed in advance. If every thread that needs both takes X first, a thread holding Y never waits for X, so the second half of the cycle cannot happen.

The dining philosophers problem shows the idea with five locks. Five philosophers sit around a table with one fork between each pair of neighbors, five forks in all, and each needs both adjacent forks to eat. If each picks up the left fork and then waits for the right one, all five can end up holding one fork and waiting forever. Number the forks 1 to 5 and require every philosopher to pick up the lower-numbered fork first. Four philosophers still pick up left, then right. The one between fork 5 and fork 1 now picks up fork 1 first, and the cycle cannot close: some philosopher can always get a second fork and eat.

How it works

  1. List the locks. Include every lock that a thread can wait for while it holds another one: the program’s own locks, and the locks inside called functions, libraries, drivers, the memory allocator and logging code. A function that takes a lock inside counts as taking that lock at the point where it is called.

  2. Assign ranks. Give each lock, or each class of similar locks, a number. The order needs to be fixed only between locks that are ever held together.

  3. Follow the rule. While holding locks, a thread may wait for a lock only if that lock’s rank is higher than the rank of every lock the thread holds. Releasing needs no rule: unlocking never waits, so locks may be released in any order.

  4. Break ties within a class. When one operation needs two locks of the same kind, such as the locks of two bank accounts, order them by a stable key, such as the account number or the lock’s memory address, and always take the smaller first.

  5. Handle exceptions explicitly. If code that holds a high-rank lock needs a lower one, it releases the high one, takes both in order, and checks again any state it read before, because another thread may have changed it in between. Alternatively, it tries to take the lower lock without waiting, called a try-lock; if that fails, it releases everything and starts again.

A rule that is only written down gets broken. Tools check it. The Linux kernel’s lock validator, lockdep, records each order in which kinds of locks are taken and reports a possible deadlock as soon as the recorded orders contain a cycle, even in a run that did not deadlock. A simpler check suits small systems: each thread records the highest rank it holds, and the lock function stops the program with an error when asked for a lock of equal or lower rank.

Worked example

Each bank account has a lock. A transfer locks both accounts, moves the money and unlocks both. Thread 1 transfers from account 17 to account 42 while thread 2 transfers from account 42 to account 17. With the rule lock the source, then the destination, thread 1 locks 17 and thread 2 locks 42; then thread 1 waits for 42 and thread 2 waits for 17, and both wait forever. With the rule lock the smaller account number first, both threads lock 17 first. Thread 2 can no longer hold 42 while it waits for 17, because it must take 17 before 42. Whichever thread gets 17 also gets 42, finishes and releases both, and then the other thread runs.

A hidden lock: the device-table lock D has rank 10 and the logging lock G has rank 20. Code that holds D may call a function log_message, which takes G inside: rank 10, then rank 20, which the rule allows. Now suppose the logging code, while holding G, calls a hook that looks up the device table and so takes D: rank 20, then rank 10, which the rule forbids. If thread 1 runs the first path while thread 2 runs the second, thread 1 holds D and waits for G, and thread 2 holds G and waits for D: a deadlock, although no single function in the program takes both locks.

Stated precisely

Write r(L)r(L) for the rank of lock LL. The rule is: a thread that holds the set of locks HH may wait for lock LL only if r(L)>r(M)r(L) > r(M) for every lock MM in HH.

Claim: if every thread obeys the rule, no cycle of threads waiting for ranked locks exists. Proof: suppose threads T1,T2,…,TkT_1, T_2, \dots, T_k form such a cycle, where TiT_i waits for lock LiL_i, held by Ti+1T_{i+1}, for i<ki < k, and TkT_k waits for lock LkL_k, held by T1T_1. Thread Ti+1T_{i+1} holds LiL_i and waits for Li+1L_{i+1}, so the rule gives r(Li)<r(Li+1)r(L_i) < r(L_{i+1}). Thread T1T_1 holds LkL_k and waits for L1L_1, so r(Lk)<r(L1)r(L_k) < r(L_1). Chained together, these give r(L1)<r(L2)<…<r(Lk)<r(L1)r(L_1) < r(L_2) < \dots < r(L_k) < r(L_1), so r(L1)<r(L1)r(L_1) < r(L_1), which is impossible.

The ranks need not be one global numbering. Draw an arrow from lock MM to lock LL whenever some thread waits for LL while holding MM. It is enough that these arrows form no cycle: a topological ordering §14.19 of them, a numbering in which every arrow goes from a lower to a higher number, then serves as the ranks.

The guarantee rests on three assumptions.

  1. Complete coverage. The rule covers every lock a thread can wait for while holding another, including locks taken inside called code.

  2. Exclusive locks. Each lock has at most one holder at a time.

  3. Lock waits only. The only waits are waits for these locks. A wait for a condition, a message, another thread’s completion or a hardware event lies outside the proof and needs its own argument.

Limits and common mistakes

Lock ordering prevents only deadlocks made of ranked locks. It does not stop waits on messages, queues or other threads from forming a cycle, and it does nothing about starvation §9.18, priority inversion §9.16 or the length of waits.

Locking the same lock twice breaks the rule, because a rank is not greater than itself. With a lock that does not allow its holder to lock it again, the thread waits for itself.

Callbacks §14.22 are the usual leak. A callback that runs while its caller holds a lock may take only locks of higher rank than that lock, and the callback’s author rarely knows which lock that is. Call code you do not control only while holding no locks.

A readers–writer lock, which admits many readers at once or one writer, belongs in the order like any other lock. Two threads that each hold a read lock and wait for the other’s write lock deadlock as surely as with mutexes §9.5.

The order says nothing about whether the data is correct. Releasing and retaking locks to restore the order opens a window in which other threads change the data, so code that does this must check its assumptions again.

A try-lock-and-back-off loop avoids deadlock but can livelock: two threads that release and retry in step forever make no progress. Random delays before retrying break the symmetry.

Tests that never deadlocked prove nothing about the order. Check the order itself, with a validator such as lockdep or with rank checks in the lock function.

Questions answered

Are hidden locks inside helpers or libraries included in the order?

Yes, hidden locks inside helpers and libraries are included in the lock order. A deadlock depends on which locks a thread holds and waits for at run time, not on which source file contains the lock call. If a thread that holds lock Y calls a helper that takes lock X inside, the thread has taken Y and then X, exactly as if it had written both calls itself. If another path takes X and then Y, the two paths can deadlock.

Typical hidden locks are those inside the memory allocator, logging and printing functions, file systems, flash and cryptography drivers, and many libraries that are safe to call from several threads. For each such lock, either give it a rank in the order, or make sure the program holds none of its own locks when it calls into that code. A library whose internal locks are unknown is safest called with no locks held. If the library calls back into the program while holding its own lock, its documentation must say which locks the callback may take.

Related entries: Deadlock (§9.14), Starvation (§9.18), Topological ordering (§14.19), Reentrancy (§9.27).