Codacoda
Back to Academy

concurrency

Deadlock

A deadlock occurs when two or more threads are each waiting for a resource held by the other, creating a circular dependency that halts all progress. The four necessary conditions for deadlock are mutual exclusion, hold and wait, no preemption, and circular wait. Preventing deadlock requires breaking at least one of these conditions. The most common strategy is enforcing a consistent lock ordering so circular waits cannot form.

Use Cases

  • Detecting and preventing circular lock dependencies in database transactions
  • Designing resource acquisition hierarchies in operating systems
  • Avoiding deadlocks in multi-threaded banking transfer systems
  • Debugging hung applications where threads are permanently blocked

Visualization

INITIALResource AResource BThread 1idleThread 2idle
Speed:1x
Two threads each need two resources. A classic deadlock scenario is about to unfold.Step 1 / 7

Implementation

Output

Click "Run Code" to see output...