Skip to content
We areTOP 1%

What are the methods for handling deadlocks?

MediumConceptDeadlocks
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

There are four strategies, which differ in when the system acts:

  • Prevention: design rules so that one Coffman condition can never hold, for example request all resources at once (no hold and wait) or acquire resources in a fixed global order (no circular wait). It is simple but can waste resources.
  • Avoidance: before granting each request, check that the system will stay in a safe state, one from which every process can still finish in some order. The Banker's algorithm does this, but processes must declare their maximum needs in advance.
  • Detection and recovery: allow deadlocks, periodically look for cycles in a resource-allocation (wait-for) graph, then recover by killing a process or preempting its resources and rolling it back.
  • Ignore it (the "ostrich algorithm"): assume deadlocks are rare and leave them to programmers or a restart. Linux and Windows take this approach for application locks, because the other methods cost too much performance.

Example: a banking program locks two accounts for every transfer. With prevention, it always locks the account with the smaller ID first, so transfer(A → B) and transfer(B → A) both lock A first and can never wait on each other. Databases such as MySQL (InnoDB) use detection instead: they find the cycle and roll back one transaction.

More in Deadlocks

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account