Master the fundamental concepts of threads & concurrency through this focused micro-challenge.
Barriers synchronize phases: no thread enters phase two until all threads finish phase one. Scientific simulations use them each timestep; thread pools use variants when joining forked work.
Operations:
For example, 4 threads computing a matrix row each call barrier_wait(); printing results before all 4 arrive would read incomplete rows.
POSIX's pthread_barrier_wait and MPI's MPI_Barrier implement exactly this pattern to synchronize compute phases in HPC codes like Jacobi iteration and parallel matrix multiplication, where correctness depends on every rank finishing phase N before any starts phase N+1. The generation-counter trick you implement here is what makes the barrier cyclic and safe to reuse across phases without a lost-wakeup race, the same issue naive reusable barriers in early parallel libraries got wrong.
Before you call the implementation done, walk failure modes on purpose. Test empty structures, single-element edge cases, maximum concurrency, and errno paths that must not crash the program. OS code usually fails in production when happy-path tests pass but invariants break under contention or memory pressure.
Keep structures small and name fields after kernel counterparts when possible. That lets you read man pages and kernel source side by side while you work. Print observable events during development; remove noisy logs once tests pass reliably.
You will implement a sense-reversing or mutex/cond barrier for a fixed thread count. The task asks you to run a phased computation where phase B output depends on all phase A completions.
Implement barrier synchronization.
Requirements:
Test:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github