← Lessons

quiz vs the machine

Gold1360

Concurrency

The Lock Ordering Discipline

Acquire locks in a fixed global order to make deadlock cycles impossible.

4 min read · core · beat Gold to climb

Why ordering prevents deadlock

A deadlock cycle needs threads to wait in a loop. If every thread always takes locks in the same global order, no cycle can form, so deadlock becomes impossible by construction.

How to enforce it

Assign every lock a rank, then require that a thread only acquires a lock whose rank is higher than any it already holds:

  • pick a total order over all locks, such as by address or by name
  • always lock lower ranked before higher ranked
  • if you need a lower ranked lock later, release and reacquire in order

A runtime checker can verify the rule by tracking each threads held set.

The cost

The discipline can force awkward code when natural acquisition order differs from the rank, and it requires every contributor to follow the rule everywhere.

Key idea

Acquiring locks in one global rank order removes the cycle a deadlock needs, trading some code awkwardness for a guarantee that no waiting loop can form.

Check yourself

Answer to earn rating on the learn ladder.

1. Why does a global lock order prevent deadlock?

2. What must a thread do to take a lower ranked lock it skipped?