LATCHES C++ Introduction














































LATCHES C++ Introduction



INTRODUCTION to LATCHES

Latches are a thread co-ordination mechanism that allow one or more threads to block until an operation is completed. An individual latch is a single-use object; once the operation has been completed, it cannot be re-used.
In other words,
  • std::latch is a counter that counts down. 
  • Its value is set in the constructor. A thread can decrement the counter by using the method thread.count_down_and_wait and wait until the counter becomes zero. 
  • The method thread.count_down only decrease the counter by 1 without waiting. std::latch has further the method thread.is_ready in order to test if the counter is zero and it has the method thread.wait to wait until the counter becomes zero. 
  • You have no possibility to increment or reset the counter of a std::latch, hence you can not reuse it. 
Member Functions are:

constructor( size_t );
The parameter is the initial value of the internal counter.

destructor( );
Destroys the latch.However, if the latch is destroyed while other threads are in wait(), or are invoking count_down(), the behaviour is undefined.

void count_down( );
Decrements the internal count by 1, and returns. If the count reaches 0, any threads blocked in wait() will be released.

Throws std::logic_error if the internal count is already 0.

void wait( );
Blocks the calling thread until the internal count is decremented to 0 by one or more other threads calling count_down(). If the count is already 0, this is a no-op.

bool try_wait( );
Returns true if the internal count has been decremented to 0 by one or more other threads calling count_down(), and false otherwise. Does not block the calling thread.

void count_down_and_wait( );
Decrements the internal count by 1. If the resulting count is not 0, blocks the calling thread until the internal count is decremented to 0 by one or more other threads calling count_down().

Can read more from the proposal n4204.

                                     ________________________________________________


Comments