Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::latch — one-shot waiting for a counter to reach zero

std::latch from <latch> lets threads wait for a counter to reach zero. count_down() reports completion of a unit of work, while wait() waits for the countdown to finish without changing the counter.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <latch>
std::latch done{expected};
done.count_down();
done.wait();

std::latch is a one-shot synchronization mechanism from <latch>. Its constructor sets the counter to expected, which must satisfy 0 <= expected && expected <= std::latch::max(). The counter represents outstanding arrivals, not necessarily distinct threads. After reaching zero, the object cannot be reset or reused for another round.

std::latch::count_down(update) atomically subtracts update, defaulting to 1. It requires 0 <= update, and update must not exceed the current counter; therefore, do not call the default count_down() after zero. This method does not wait for other arrivals. std::latch::wait() does not decrement the counter: it blocks until zero, or returns immediately if the counter is already zero. Missing arrivals can leave it waiting indefinitely.

In C++23, count_down() strongly happens before returns from calls that are unblocked on the latch. This guarantee does not explicitly cover a wait() that starts after the counter has reached zero. In the example, worker can call count_down() before the main thread calls wait(), so wait() alone does not guarantee that the non-atomic read of result is safe under every thread schedule. The latch does not protect arbitrary concurrent writes to shared data either.

The object must remain alive during operations on it. In the example, worker is destroyed before done, but the main thread does not rely on the std::jthread destructor: it explicitly calls worker.join() after wait() and before reading result. The worker thread's completion synchronizes with the successful return from worker.join(), so the read of result is safe whether or not wait() blocked. On successful execution, the program prints 42 followed by a newline.

Examples

#include <iostream>
#include <latch>
#include <thread>

int main() {
    int result = 0;
    std::latch done{1};

    std::jthread worker([&] {
        result = 42;
        done.count_down();
    });

    done.wait();
    worker.join();
    std::cout << result << '\n';
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources