multithreading · high

Deadlock & the 4 Coffman Conditions

Two threads lock A and B in opposite orders, forming a circular wait. Watch all four conditions appear - then break one to fix it.

🔑 Key line

Deadlock needs all 4 Coffman conditions; break any one (e.g. a global lock order) to prevent it.

The code

std::mutex A, B;
void t1() {
std::lock_guard la(A); // T1 locks A
std::lock_guard lb(B); // T1 then wants B
}
void t2() {
std::lock_guard lb(B); // T2 locks B
std::lock_guard la(A); // T2 then wants A
}

What this lesson walks through

  1. 01Two threads need the same two mutexes
  2. 02T1 locks A
  3. 03T2 locks B
  4. 04T1 holds A and now wants B
  5. 05T2 holds B and now wants A
  6. 06Circular wait -> deadlock
  7. 07Fix: one global lock order (A before B)

Two threads each need BOTH locks A and B - but they take them in opposite orders. That ordering mismatch is the whole problem.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Deadlock & the 4 Coffman Conditions and 100+ animated C++ interview lessons.

← Previous
C: char Signedness & sizeof Quirks
Next →
Producer-Consumer with Condition Variables