In C++20, how do std::latch, std::barrier and std::counting_semaphore differ, and which one releases a group of test threads at once?
answer
- one-shot versus reusable
- count_down, then wait
- phases and a completion step
- permits: acquire and release
basics
~20 sstd::latch is a single-use countdown: count_down to zero releases every waiter, so a latch of 1 is a start gate for test threads. std::barrier repeats in phases and runs a completion function; std::counting_semaphore counts permits with acquire and release.
solid answer
~30 sAll three arrived in C++20 (`<latch>`, `<barrier>`, `<semaphore>`) and replace common hand-written mutex-plus-condition-variable patterns. `std::latch` holds a counter set at construction; `count_down` lowers it, `wait` blocks until it reaches zero, and it can never be reset — so `std::latch start{1};` with every test thread calling `start.wait()` and the test calling `start.count_down()` releases them together. `std::barrier` is reusable: each phase ends when the expected number of threads have arrived (`arrive_and_wait`), runs the completion function once, and resets; `arrive_and_drop` lets a worker leave for good. `std::counting_semaphore<N>` holds permits: `acquire` blocks at zero, `release` adds, and `std::binary_semaphore` is `counting_semaphore<1>`. None of them is copyable.
code
cpp · 23 lines#include <atomic>
#include <barrier>
#include <cstdio>
#include <latch>
#include <thread>
#include <vector>
int main() {
constexpr int kThreads = 4;
std::latch start{1}; // one-shot gate: the test opens it once
std::atomic<int> rounds_done{0};
std::barrier sync{kThreads, [&]() noexcept { // completion runs once per phase
std::printf("phase %d complete\n", rounds_done.fetch_add(1) + 1);
}};
std::vector<std::jthread> workers;
for (int i = 0; i < kThreads; ++i)
workers.emplace_back([&] {
start.wait(); // every thread blocks here first
for (int round = 0; round < 2; ++round)
sync.arrive_and_wait(); // the barrier resets itself after each phase
});
start.count_down(); // release all test threads at once
}go deeper
Know the three names and headers from C++20 and the one-line purpose of each: one-shot countdown, repeating rendezvous, permits.
Explain the members — count_down, wait, arrive_and_wait, arrive_and_drop, acquire, release — and write a start gate for test threads with a latch of 1.
Spot misuse: a reused latch, a barrier sized wrongly, a throwing completion function, a semaphore treated as an owned mutex; replace hand-written condition-variable counters with these.
Set the team default: the C++20 primitive where it fits, a condition variable only for arbitrary predicates, and no hand-rolled countdowns.
## Why these exist Before C++20, "wait until N things have happened" or "let at most K threads in" was written by hand from a `std::mutex`, a `std::condition_variable` and a counter, with all the predicate and lost-wake-up care that needs. C++20 added three ready-made coordination types; each says what it is for and has no predicate to get wrong. The feature-test macros are `__cpp_lib_latch`, `__cpp_lib_barrier` and `__cpp_lib_semaphore`. ## `std::latch` — a one-shot countdown - Constructed as `std::latch l{expected};` with a counter. - `count_down(n = 1)` atomically lowers the counter; when it reaches zero every blocked thread is released. Lowering it below zero violates the precondition `update <= counter`. - `wait()` returns at once if the counter is zero, otherwise blocks until it reaches zero. - `arrive_and_wait(n = 1)` is `count_down(n); wait();`. - `try_wait()` reports whether the counter is zero, and the standard lets it return `false` "with very low probability" even when it is. - The standard calls it "a single-use object": there is no reset. The **start gate for test threads** is the textbook use: construct `std::latch start{1};`, have every worker call `start.wait()` first, and let the test call `start.count_down()` once all workers are created. They are released together, which makes a contention test actually contend. The reverse, `std::latch done{n};` with each worker calling `count_down()` and the coordinator `wait()`, replaces a join-all loop. ## `std::barrier` — reusable phases `std::barrier<CompletionFunction>` runs as a sequence of **phases**. In each phase: 1. Each participating thread calls `arrive()` (getting an `arrival_token` to pass to `wait`), `arrive_and_wait()`, or `arrive_and_drop()`; each lowers the expected count. 2. Exactly once after the count reaches zero, one of the participating threads runs the **completion step** inside its call to `arrive`, `arrive_and_drop` or `wait`: it calls the completion function, then unblocks every waiter. Since the C++23 wording, if no thread calls `wait` it is implementation-defined whether the step runs at all. 3. The expected count resets to the constructor's value, minus any `arrive_and_drop` calls, and the next phase starts. The completion function must be invocable without throwing: the standard requires `is_nothrow_invocable_v<CompletionFunction&>`, so a lambda is normally written `[]() noexcept { ... }`. It is the place to swap buffers or advance a round counter between phases. `arrive_and_drop()` is how a worker that has finished for good leaves without stalling later phases. ## `std::counting_semaphore` — permits `template<std::ptrdiff_t least_max_value = /* implementation-defined */> class counting_semaphore` holds a non-negative counter: - `acquire()` blocks while the counter is zero, then decrements it. - `release(n = 1)` adds `n` and unblocks waiters. - `try_acquire()`, `try_acquire_for()` and `try_acquire_until()` are the non-blocking and timed forms; the standard allows `try_acquire` to fail spuriously. - `std::binary_semaphore` is an alias for `std::counting_semaphore<1>`. A semaphore has **no owner**: any thread may `release`, which is what makes it usable for signalling but also why it is not a drop-in `std::mutex`. Two semaphores — free slots and filled slots — can bound a producer-consumer queue, but the queue's own data still needs a mutex unless it is lock-free. The default `least_max_value` is implementation-defined; libc++ uses the maximum `ptrdiff_t`. ## The hand-written start gate it replaces Before C++20 a start gate looked like this: a `std::mutex`, a `std::condition_variable` and a `bool go = false;`. Each worker locked the mutex and called `cv.wait(lk, [&]{ return go; })`; the test locked, set `go = true`, unlocked and called `notify_all()`. Every piece of that is a chance to get the protocol wrong — a `notify_one` instead of `notify_all`, the flag set without the mutex, a bare `wait` with no predicate. With `std::latch start{1};` the whole protocol is two calls, `start.wait()` and `start.count_down()`, and the library owns the correctness. The condition variable is still the right tool when the condition is an arbitrary predicate over shared data, such as "the queue is not empty". ## Choosing | Need | Type | |---|---| | Release N threads together once, or wait for N completions once | `std::latch` | | Repeat a rendezvous every round, with work between rounds | `std::barrier` | | Limit concurrent access to K, or signal "one item available" | `std::counting_semaphore` | | Wait for an arbitrary condition on shared data | `std::condition_variable` with a predicate | ## Pitfalls - Reusing a `std::latch` across test iterations: after it reaches zero, every later `wait()` returns immediately. - Constructing a barrier with fewer participants than the threads that call `arrive_and_wait`: a phase can complete before every worker has arrived, and the late arrivals land in the next phase. - Throwing from a barrier completion function. - Treating `std::binary_semaphore` as a mutex and expecting deadlock detection or ownership checks. - All three are neither copyable nor movable; share them by reference or pointer.
- What happens if a test reuses a std::latch for a second round?Nothing waits. A `std::latch` is single-use: once its counter has reached zero, `wait()` returns immediately and there is no member to reset it. A second round needs a new latch, or a `std::barrier`, which resets its expected count at the end of each phase.
- Can a std::binary_semaphore replace a std::mutex?It can provide mutual exclusion, but it has no owner: any thread may call `release`, so a bug that releases from the wrong thread goes unnoticed, and nothing like `std::lock_guard` or `std::unique_lock` is built for it. It suits signalling between threads; for protecting data a `std::mutex` with an RAII lock is the clearer tool.
- A std::latch resets itself once it reaches zero
- std::barrier runs the completion function in every arriving thread
- A semaphore release must come from the thread that acquired it
- count_down on a std::latch blocks until the count reaches zero
- These types exist only from C++23 onward
Assumes C++20 or later: std::latch, std::barrier and std::counting_semaphore were added in C++20; C++23 revised the wording of the barrier completion step (__cpp_lib_barrier 202302L).