Synchronization PatternsBarrier SynchronizationHard⏱️ ~2 min

Barrier Deadlocks: What Can Go Wrong

Warning
Barrier implementations have subtle deadlock traps. Blocking while holding a mutex is the classic mistake.

Deadlock 1: Waiting Inside the Mutex

Tempting but wrong: put the barrier wait inside the mutex. Thread 1 locks mutex, increments count, waits on barrier. But it is holding the mutex! No other thread can increment count. Count never reaches N. Barrier never opens. Deadlock.

Deadlock: Waiting While Holding Mutex
Thread 1holds mutexblocked on barrierThreads 2-Nneed mutex to incrementblocked on mutexDEADLOCK

Deadlock 2: Missing Turnstile Signal

The Nth thread signals the barrier, releasing one waiting thread. But if that thread does not signal, the remaining N-2 threads stay blocked forever. The barrier opened for one thread, then slammed shut.

The Golden Rule

Never block on a semaphore while holding a mutex. This is a recipe for deadlock. Always release the mutex before waiting on any blocking operation.

Correct Structure

Lock mutex, update counter, unlock mutex, THEN check count and wait on barrier. The mutex protects only the counter update, not the blocking wait. Other threads can increment while you wait.

Deadlock Prevention: Separate counter protection from barrier waiting. Mutex scope should be minimal: just the counter increment. Release mutex before any wait().
💡 Key Takeaways
Never wait on barrier while holding mutex. Other threads cannot increment count. Deadlock guaranteed.
Turnstile signal is mandatory. Without it, only one thread escapes the barrier. Others block forever.
Golden rule: release mutex before any blocking operation. Mutex protects data, not synchronization points.
Correct pattern: lock, increment, unlock, then check and wait. Keep mutex scope minimal.
These deadlocks are subtle - code looks reasonable but fails under specific timing.
📌 Examples
1Wrong: mutex.lock(); count++; barrier.wait(); mutex.unlock(); - Deadlock! Thread holds mutex while waiting.
2Right: mutex.lock(); count++; mutex.unlock(); if(count==n) barrier.signal(); barrier.wait(); barrier.signal();
3Missing turnstile: N=5, four threads block, fifth signals, one wakes, four still blocked. Classic bug.
← Back to Barrier Synchronization Overview
Barrier Deadlocks: What Can Go Wrong | Barrier Synchronization - System Overflow