AlgoViz

Deadlocks and lock order

hard 65 min

Two threads, two locks, and a program that waits for ever.

Watch lesson5:12

Where it shows up

The same pattern appears across everyday software.

  • PostgreSQL

    It detects deadlocks and aborts one of the transactions involved. It looks after `deadlock_timeout`, one second by default, and its manual advises a consistent lock order and retries.

  • Linux kernel lockdep

    A runtime validator that learns the order between **classes** of locks and reports a wrong order even if no deadlock has happened.

  • Java ThreadMXBean

    `findDeadlockedThreads` finds cycles of platform threads that wait for monitors or ownable synchronizers in a running virtual machine.

  • Guava CycleDetectingLockFactory

    Makes Java locks that track the order in which they are taken and report a potential cycle, by a warning or an exception.

  • C++ std::scoped_lock

    Takes several mutexes at once with a deadlock avoidance algorithm, and opens them when the scope ends.

  • Abseil Mutex

    Google's C++ mutex has a deadlock detector that notices locks taken in an inconsistent order. It is on by default in most builds that are not optimized.

  • Go runtime

    When no goroutine can ever run again, it stops the program with: all goroutines are asleep - deadlock! It does not notice a circle of a few while others still run.

  • Clang thread safety analysis

    `ACQUIRED_BEFORE` and `ACQUIRED_AFTER` state the order of mutexes in the source, for a check at compile time.

  • Rust parking_lot

    An optional, experimental feature lets a background thread look for deadlocks among its locks and print their backtraces.

  • Python faulthandler

    Prints the stacks of all threads after a timeout, also when the program is deadlocked. Useful around a test that may hang.