Barrier Deadlocks: What Can Go Wrong
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 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.