33 Concurrency support library [thread]

33.9 Coordination types [thread.coord]

33.9.2 Latches [thread.latch]

33.9.2.1 General [thread.latch.general]

A latch is a thread coordination mechanism that allows any number of threads to block until an expected number of threads arrive at the latch (via the count_down function).
The expected count is set when the latch is created.
An individual latch is a single-use object; once the expected count has been reached, the latch cannot be reused.

33.9.2.2 Header <latch> synopsis [latch.syn]

namespace std { class latch; }

33.9.2.3 Class latch [thread.latch.class]

namespace std { class latch { public: static constexpr ptrdiff_t max() noexcept; constexpr explicit latch(ptrdiff_t expected); ~latch(); latch(const latch&) = delete; latch& operator=(const latch&) = delete; void count_down(ptrdiff_t update = 1); bool try_wait() const noexcept; void wait() const; void arrive_and_wait(ptrdiff_t update = 1); private: ptrdiff_t counter; // exposition only }; }
A latch maintains an internal counter that is initialized when the latch is created.
Threads can block on the latch object, waiting for counter to be decremented to zero.
Concurrent invocations of the member functions of latch, other than its destructor, do not introduce data races.
static constexpr ptrdiff_t max() noexcept;
Returns: The maximum value of counter that the implementation supports.
constexpr explicit latch(ptrdiff_t expected);
Preconditions: expected >= 0 is true and expected <= max() is true.
Effects: Initializes counter with expected.
Throws: Nothing.
void count_down(ptrdiff_t update = 1);
Preconditions: update >= 0 is true, and update <= counter is true.
Effects: Atomically decrements counter by update.
If counter is equal to zero, unblocks all threads blocked on *this.
Synchronization: Strongly happens before the returns from all calls that are unblocked.
Throws: system_error when an exception is required ([thread.req.exception]).
Error conditions: Any of the error conditions allowed for mutex types ([thread.mutex.requirements.mutex]).
bool try_wait() const noexcept;
Returns: With very low probability false.
Otherwise counter == 0.
void wait() const;
Effects: If counter equals zero, returns immediately.
Otherwise, blocks on *this until a call to count_down that decrements counter to zero.
Throws: system_error when an exception is required ([thread.req.exception]).
Error conditions: Any of the error conditions allowed for mutex types ([thread.mutex.requirements.mutex]).
void arrive_and_wait(ptrdiff_t update = 1);
Effects: Equivalent to: count_down(update); wait();