Synchronization Patterns • Barrier SynchronizationMedium⏱️ ~2 min
Implementing a Barrier: The Counter Approach
Core Idea
Count arriving threads with a protected counter. When count reaches N, release everyone through a turnstile.
The Components
count: Tracks how many threads have arrived. Starts at 0.
mutex: Protects the counter from concurrent updates.
barrier semaphore: Initialized to 0 (locked). Blocks threads until all arrive.
The Algorithm
Each thread: (1) Lock mutex, increment count, unlock mutex. (2) If count equals N, signal the barrier. (3) Wait on barrier. (4) Signal barrier (let next thread through).
Barrier Flow (N=3)
The Turnstile Pattern
After waiting, each thread immediately signals. This creates a chain reaction: thread wakes, signals, next thread wakes, signals, and so on. All N threads pass through one at a time in rapid succession.
Why Signal After Wait?
Without it, only one thread passes. The Nth thread signals once, one blocked thread wakes, but the others remain stuck. The turnstile (wait-then-signal) propagates the release to all waiting threads.
Key Pattern: wait() then signal() creates a turnstile. One thread unlocks it, then each passing thread keeps it open for the next. All N threads flow through.
💡 Key Takeaways
✓Use a counter (protected by mutex) to track arrivals. When count equals N, release the barrier.
✓Barrier semaphore starts at 0 (locked). The Nth thread signals it, releasing one blocked thread.
✓Turnstile pattern: each thread does wait() then signal(). Creates chain reaction releasing all threads.
✓Without the post-wait signal, only one thread escapes. The turnstile propagates the unlock to everyone.