Additional Synchronization Primitives in C++20

Learn about the new synchronization primitives in C++20 (latches and barriers) and how they're used.

C++20 comes with a few additional synchronization primitives, namely std::latch, std::barrier, and std::counting_semaphore (and the template specialization std::binary_semaphore). This lesson will be an overview of these new types and some typical scenarios where they can be useful. We’ll begin with std::latch.

Using latches

A latch is a synchronization primitive that can be used for synchronizing multiple threads. It creates a synchronization point where all threads must arrive at. We can think of a latch as a decrementing counter. Typically, all threads decrement the counter once and then wait for the latch to reach zero before moving on.

A latch is constructed by passing an initial value of the internal counter:

Get hands-on with 1200+ tech skills courses.