CKTIS / C++
std::barrier: a reusable phase rendezvous
std::barrier synchronizes a fixed group of participants at each phase boundary and then automatically starts the next phase.
Version: C++23
Syntax
template<class CompletionFunction = /* unspecified */>
class barrier {
public:
explicit barrier(std::ptrdiff_t expected, CompletionFunction completion = CompletionFunction());
void arrive_and_wait();
arrival_token arrive(std::ptrdiff_t update = 1);
void wait(arrival_token&& arrival) const;
void arrive_and_drop();
};std::barrier from <barrier> maintains an expected arrival count for each phase. arrive_and_wait() arrives and blocks, arrive() returns a token for a later wait(), and arrive_and_drop() also permanently reduces the participant count for subsequent phases. std::barrier::arrive_and_wait records one arrival and waits for the phase to complete. std::barrier::arrive_and_drop records an arrival without waiting and permanently reduces the expected arrival count of subsequent phases by one.
When the count reaches zero, the completion step normally runs exactly once; however, if no thread calls wait (including through arrive_and_wait), whether the step runs is implementation-defined. When it runs, waiters are unblocked and the count resets for the next phase. The end of completion strongly happens before the returns of unblocked waits, so participants’ writes before arrival can be observed safely after waiting.
The expected argument must be between zero and max(); with zero, the object can only be destroyed. Every participant must honor the arrival protocol or others can wait forever. A barrier is not copyable and must outlive every thread or arrival token that can still use it.
Examples
#include <barrier>
#include <iostream>
#include <thread>
int main() {
int value = 0;
std::barrier phase{2};
std::jthread worker([&] {
value = 7;
phase.arrive_and_wait();
});
phase.arrive_and_wait();
std::cout << value << '\n';
}
Result
7
std::barrier → 7