Files
2025-10-25 03:02:53 +03:00

5.8 KiB

[thread.latch]

32 Concurrency support library [thread]

32.9 Coordination types [thread.coord]

32.9.2 Latches [thread.latch]

32.9.2.1 General [thread.latch.general]

1

#

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.

32.9.2.2 Header synopsis [latch.syn]

🔗

namespace std {class latch;}

32.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};}

1

#

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.

2

#

Concurrent invocations of the member functions of latch, other than its destructor, do not introduce data races.

🔗

static constexpr ptrdiff_t max() noexcept;

3

#

Returns: The maximum value of counter that the implementation supports.

🔗

constexpr explicit latch(ptrdiff_t expected);

4

#

Preconditions: expected >= 0 is true andexpected <= max() is true.

5

#

Effects: Initializes counter with expected.

6

#

Throws: Nothing.

🔗

void count_down(ptrdiff_t update = 1);

7

#

Preconditions: update >= 0 is true, andupdate <= counter is true.

8

#

Effects: Atomically decrements counter by update.

If counter is equal to zero, unblocks all threads blocked on *this.

9

#

Synchronization: Strongly happens before the returns from all calls that are unblocked.

10

#

Throws: system_error when an exception is required ([thread.req.exception]).

11

#

Error conditions: Any of the error conditions allowed for mutex types ([thread.mutex.requirements.mutex]).

🔗

bool try_wait() const noexcept;

12

#

Returns: With very low probability false.

Otherwise counter == 0.

🔗

void wait() const;

13

#

Effects: If counter equals zero, returns immediately.

Otherwise, blocks on *this until a call to count_down that decrements counter to zero.

14

#

Throws: system_error when an exception is required ([thread.req.exception]).

15

#

Error conditions: Any of the error conditions allowed for mutex types ([thread.mutex.requirements.mutex]).

🔗

void arrive_and_wait(ptrdiff_t update = 1);

16

#

Effects: Equivalent to:count_down(update); wait();