Synchronization PatternsBarrier SynchronizationMedium⏱️ ~2 min

Barriers in Practice: APIs and Use Cases

Practical Guide
Every major language provides barrier primitives. Know the API, the quirks, and when a barrier is the right tool.

Java: CyclicBarrier

Create with thread count: new CyclicBarrier(n). Threads call await(). Automatically resets after each cycle. Can specify a barrier action that runs once when all arrive.

C/C++: pthread_barrier

Initialize with pthread_barrier_init(&b, NULL, count). Threads call pthread_barrier_wait(&b). One thread gets special return value (PTHREAD_BARRIER_SERIAL_THREAD) to run cleanup.

Go: sync.WaitGroup (Barrier-like)

Not exactly a barrier, but often used similarly. Add(n) sets count, workers call Done(), main thread calls Wait(). Good for fork-join patterns.

When to Use a Barrier
Good FitPhased computationAll threads must syncRepeated iterationsPoor FitVariable thread countSome threads may failThreads finish at different times

When NOT to Use Barriers

Dynamic thread count: Barrier requires fixed N. If threads can come and go, use other primitives.

Thread failure: If one thread crashes, others wait forever. Need timeouts or cancellation.

Asymmetric workloads: Fast threads waste time waiting. Consider work-stealing instead.

Best Practice: Use barriers for symmetric, fixed-size, failure-free parallel phases. For anything else, consider producer-consumer, futures, or async patterns.
💡 Key Takeaways
Java CyclicBarrier: await() blocks until all arrive, auto-resets, supports barrier action callback.
pthread_barrier_wait: one thread gets SERIAL return value for post-barrier cleanup work.
Go WaitGroup is barrier-like but asymmetric: workers Done(), one waiter Wait(). Not true barrier.
Barriers need fixed thread count. Dynamic workloads need different patterns.
Thread failure breaks barriers. Production code needs timeouts or health checking.
📌 Examples
1CyclicBarrier with action: new CyclicBarrier(n, () -> mergeResults()). mergeResults runs once when all arrive.
2pthread serial thread: if (pthread_barrier_wait(&b) == PTHREAD_BARRIER_SERIAL_THREAD) { writeOutput(); }
3Failure scenario: 4-thread barrier, one thread throws exception. Other 3 wait forever. Need try-catch + timeout.
← Back to Barrier Synchronization Overview
Barriers in Practice: APIs and Use Cases | Barrier Synchronization - System Overflow