07

Chapter 07: A Barrier-Phased Worker Pool

std::barrier's completion function is the natural place to merge per-thread partial results between phases, since the standard guarantees it runs exactly once per phase.

Demo 07Source on GitHub ↗

The full source for this example lives in examples/concurrency/07-coordination-primitives/; clone the repo, cd in, and ./demo.sh.

Chapter reference: Doc 07: Coordination Primitives

What it shows

A fixed pool of workers runs through several std::barrier-synchronized phases; in each phase every worker writes into its own slot and arrives at the barrier, and the barrier’s completion function merges all the slots into a running total before releasing everyone into the next phase. Because no two workers ever write the same slot, and the barrier itself establishes the happens-before edge between every write and the completion function’s read, the merge needs no additional lock. The verifier checks that every phase produces exactly one completion line (never zero, never more than one) and that the final merged total matches an independently computed closed-form sum, both as hard assertions since a barrier’s contract is a standard guarantee, not a race.

Running it

cd examples/concurrency/07-coordination-primitives
./demo.sh            # build + run barrier_workers + verify.lua
./demo.sh --clean    # remove the image