Skip to content

std::latch

  • A std::latch can be used by one or more threads to wait until a counter becomes zero
  • a latch can be used only once, for repeated waiting use a std::barrier
  • latches and barriers are easier to use and more performant (lock-free) than other means of synchronization like futures or condition variables

Basic example:

#include <latch>

std::latch workDone(2); // prepare for 2 workers

class Worker
{
public:
    Worker(const std::string& in_name) : m_name(in_name) {}
    void operator()()
    {
        // do some work ...
        std::cout << m_name << ": ready" << "\n";

        // Signal that work is done
        workDone.count_down();
    }
private:
    std::string m_name;
};

void TestLatch()
{
    std::cout << "Start 2 workers" << "\n";

    Worker peter("  Peter");
    std::jthread peterWork(peter);

    Worker john("    John");
    std::jthread johnWork(john);

    workDone.wait();

    std::cout << "All workers are finished" << "\n";
}

Output:

Start 2 workers
  Peter: ready
    John: ready
All workers are finished

Remark: Method arrive_and_wait() is equivalent to calling count_down() and wait().

For more info see https://en.cppreference.com/w/cpp/thread/latch