Synchronization Patterns • Barrier SynchronizationHard⏱️ ~2 min
Reusable Barriers
Challenge
A reusable barrier resets itself after all threads pass. Threads can synchronize at the same barrier repeatedly in a loop.
The Problem With Simple Barriers
The basic barrier leaves count at N after everyone passes. Next iteration, count is still N, so the first thread thinks everyone has arrived. It signals immediately. Chaos. Threads proceed at random times.
The Two-Phase Approach
Use two turnstiles. Phase 1: threads arrive, last one opens turnstile 1, all pass through. Phase 2: threads decrement counter, last one opens turnstile 2. Now the barrier is reset for next use.
Two-Phase Barrier
Why Two Phases?
A fast thread might pass through the barrier, do its work, and come back for the next iteration before slow threads finish the first. Two phases ensure no thread starts iteration 2 until all have completed iteration 1.
The Sense Reversal Trick
Alternative approach: use a boolean flag that flips each iteration. Threads wait for the flag to match their expected sense. Simpler than two turnstiles, used in many production implementations.
Real Libraries: Java CyclicBarrier, pthread_barrier, and Go sync.WaitGroup handle reusability automatically. Understand the concept, but use battle-tested implementations.
💡 Key Takeaways
✓Simple barriers break on reuse. Count stays at N, next iteration triggers immediately without waiting.
✓Two-phase barrier: phase 1 counts up to open, phase 2 counts down to reset. Barrier ready for reuse.
✓Two phases prevent fast threads from lapping slow ones. Everyone finishes iteration 1 before anyone starts 2.
✓Sense reversal is an alternative: flip a boolean each iteration. Simpler implementation, same guarantee.
✓Production code should use library barriers (CyclicBarrier, pthread_barrier). They handle edge cases.
📌 Examples
1Simulation loop: compute step, barrier, check collisions, barrier, render, barrier. Same barrier reused each frame.
2Bug without reset: iteration 1 completes, fast thread arrives for iteration 2, count is N, immediately proceeds. Race condition.
3Java CyclicBarrier: automatically resets after all threads pass. Can specify a barrier action to run once per cycle.