Lock ordering¶
Category: Synchronization · Status: stub · Lessons: chapter 03, When locks go wrong (planned)
One line: Always taking locks in one agreed order, so that no cycle of tasks waiting on each other — and so no deadlock — can form.
Also called: lock hierarchy.
How it connects¶
flowchart LR
n_deadlock["Deadlock"]
n_lock_ordering["Lock ordering"]
n_lock_ordering -->|prevents| n_deadlock
classDef center stroke-width:3px
class n_lock_ordering center
classDef outside stroke-dasharray: 4 3
class n_deadlock outside
- Helps prevent: Deadlock
In each language¶
| C++ | std::lock ↗ takes several mutexes with a deadlock avoidance algorithm instead of a fixed order |
| Java | JLS §17.1 ↗ tells programs holding locks on multiple objects to use conventional deadlock-avoidance techniques |
| The operating system | Linux lockdep ↗ records which lock is taken while holding which, and reports orders that could form a cycle |
| Elsewhere | Valgrind's Helgrind ↗ monitors the order threads acquire locks in to find potential deadlocks; ThreadSanitizer ↗ reports lock-order inversions (detect_deadlocks) |
Where to read more¶
- In the books: Learn Concurrent Programming with Go, James Cutajar — ch. 11, 'Avoiding deadlocks'
- In the books: Multi-Threaded Programming in C++, Mark Walmsley — ch. 8, 'Multiple Mutexes'
- In the books: Python Parallel Programming Cookbook, Giancarlo Zaccone — ch. 3, 'Process-based Parallelism' → 'Avoiding deadlock problems'
- In the books: The Art of Multiprocessor Programming, Maurice Herlihy, Nir Shavit — ch. 7, 'Spin Locks and Contention' → 'Hierarchical Locks'
- In the books: Advanced Programming in the UNIX Environment, W. Richard Stevens, Stephen A. Rago — ch. 11, 'Threads' → 'Deadlock Avoidance'
- In the books: Operating System Concepts, Abraham Silberschatz, Peter Baer Galvin, Greg Gagne — ch. 8, 'Deadlocks' → 'Deadlock Prevention'
- Reference: Wikipedia: Dining philosophers problem ↗