Table of Contents

<barrier>

<barrier> provides a synchronization point where a fixed number of threads wait until all have arrived. Once the count is reached, all are released together.

It's useful for parallel algorithms where you need all workers to complete a stage before proceeding to the next, such as in phase-based simulations or MapReduce-style processing.

Example

This example synchronizes three threads at a barrier, ensuring that all threads report completion of phase 1 before moving to phase 2.

// compile: g++ -std=c++20 -pthread -o barrierexample barrierexample.cpp
// run: ./barrierexample
// description: synchronize 3 threads at a barrier
 
#include <barrier>
#include <iostream>
#include <thread>
 
int main() {
    std::barrier sync(3);
 
    auto worker = [&](int id) {
        std::cout << "thread " << id << " starting phase 1\n";
        sync.arrive_and_wait();
        std::cout << "thread " << id << " all threads done, moving to phase 2\n";
    };
 
    std::thread t1(worker, 1);
    std::thread t2(worker, 2);
    std::thread t3(worker, 3);
 
    t1.join();
    t2.join();
    t3.join();
 
    return 0;
}