Barriers in Practice: APIs and Use Cases
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 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.