From cppreference.com
classlatch;(since C++20)The latch class is a downward counter of type
which can be used to synchronize threads. The value of the counter is initialized on creation. Threads may block on the latch until the counter is decremented to zero. There is no possibility to increase or reset the counter, which makes the latch a single-use barrier.
Concurrent invocations of the member functions of std::latch, except for the destructor, do not introduce data races.
Data Members
Name Definition
counterthe internal counter
(exposition-only member object*)Member functions
constructs a latch
(public member function)
destroys the latch
(public member function)
operator=
[deleted]
latch is not assignable
(public member function)
decrements the counter in a non-blocking manner
(public member function)
tests if the internal counter equals zero
(public member function)
blocks until the counter reaches zero
(public member function)
decrements the counter and blocks until it reaches zero
(public member function)
Constants
[static]
the maximum value of counter supported by the implementation
(public static member function)
Notes
macroValueStdFeature
(C++20)std::latchExample
Run this code
#include<functional>#include<iostream>#include<latch>#include<string>#include<thread>structJob{conststd::stringname;std::stringproduct{"not worked"};std::threadaction{};};intmain(){Jobjobs[]{{"Annika"},{"Buru"},{"Chuck"}};std::latchwork_done{std::size(jobs)};std::latchstart_clean_up{1};autowork=[&](Job&my_job){my_job.product=my_job.name+" worked";work_done.count_down();start_clean_up.wait();my_job.product=my_job.name+" cleaned";};std::cout<<"Work is starting... ";for(auto&job:jobs)job.action=std::thread{work,std::ref(job)};work_done.wait();std::cout<<"done:\n";for(autoconst&job:jobs)std::cout<<" "<<job.product<<'\n';std::cout<<"Workers are cleaning up... ";start_clean_up.count_down();for(auto&job:jobs)job.action.join();std::cout<<"done:\n";for(autoconst&job:jobs)std::cout<<" "<<job.product<<'\n';}Output:
Work is starting... done: Annika worked Buru worked Chuck worked Workers are cleaning up... done: Annika cleaned Buru cleaned Chuck cleaned See also