Skip to content

Threading & Deadlocks — Simple#

flowchart LR
  T1[Thread A<br/>holds L1, wants L2]
  T2[Thread B<br/>holds L2, wants L1]
  L1([Lock 1])
  L2([Lock 2])
  T1 -- holds --> L1
  T2 -- holds --> L2
  T1 -- waits --> L2
  T2 -- waits --> L1

  classDef p fill:#dbeafe,stroke:#1e40af,stroke-width:1px,color:#0f172a;
  classDef s fill:#fef3c7,stroke:#92400e,stroke-width:1px,color:#0f172a;
  class T1,T2 p;
  class L1,L2 s;

    classDef client fill:#dbeafe,stroke:#1e40af,stroke-width:1px,color:#0f172a;
    classDef edge fill:#cffafe,stroke:#0e7490,stroke-width:1px,color:#0f172a;
    classDef service fill:#fef3c7,stroke:#92400e,stroke-width:1px,color:#0f172a;
    classDef datastore fill:#fee2e2,stroke:#991b1b,stroke-width:1px,color:#0f172a;
    classDef cache fill:#fed7aa,stroke:#9a3412,stroke-width:1px,color:#0f172a;
    classDef queue fill:#ede9fe,stroke:#5b21b6,stroke-width:1px,color:#0f172a;
    classDef compute fill:#d1fae5,stroke:#065f46,stroke-width:1px,color:#0f172a;
    classDef storage fill:#e5e7eb,stroke:#374151,stroke-width:1px,color:#0f172a;
    classDef external fill:#fce7f3,stroke:#9d174d,stroke-width:1px,color:#0f172a;
    classDef obs fill:#f3e8ff,stroke:#6b21a8,stroke-width:1px,color:#0f172a;
    class T1,T2,L1,L2 service;

A deadlock happens when two or more threads form a cycle of "I hold this, I want yours". Prevention is about breaking the four Coffman conditions: mutual exclusion, hold-and-wait, no preemption, circular wait.