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.