wiki:hpp-latch
<latch>
<latch> provides std::latch, a simple synchronization primitive that counts down to zero. Threads call count_down() or count_down_and_wait() to decrement; other threads call wait() to block until the count reaches zero.
Unlike std::barrier, a latch is one-time use. It's useful for waiting for a fixed number of async tasks to complete.
Example
This example uses a latch to wait for three worker threads to complete their tasks before the main thread continues.
// compile: g++ -std=c++20 -pthread -o latchexample latchexample.cpp // run: ./latchexample // description: wait for multiple threads using latch #include <latch> #include <iostream> #include <thread> int main() { std::latch done(3); auto worker = [&](int id) { std::cout << "thread " << id << " working\n"; done.count_down(); }; std::thread t1(worker, 1); std::thread t2(worker, 2); std::thread t3(worker, 3); done.wait(); std::cout << "all threads done\n"; t1.join(); t2.join(); t3.join(); return 0; }
wiki/hpp-latch.md · Last modified: by 127.0.0.1
