Synchronization Primitives in C++20 -- Shivam Kunwar

El5Swmxm_400x400.jpgIn C++20, the standard library introduced new synchronization primitives: std::latch and std::barrier. These are the utilities designed to coordinate between concurrent threads.

Synchronization Primitives in C++20

by Shivam Kunwar

From the article:

What is a synchronization primitive?

In concurrent programming, synchronization primitives are the fundamental tools that help in managing the coordination, execution order, and data safety of multiple threads or processes that run concurrently.

Briefly said, they ensure that:

  • multiple threads don’t simultaneously execute some specific segment of code (a “critical section”)
  • the program and the data remain in a consistent state
  • deadlocks (where threads wait indefinitely for resources) and race conditions (where the outcome depends on the timing of accessing the shared data by a thread) are prevented or managed

There are multiple synchronization primitives in C++; for example, mutual exclusion, condition variables, atomic operations, locking mechanisms, etc.

In C++20, we have two additional synchronization primitives: latches and barriers.

Let’s discuss both of them.

std::latch

A std::latch is a synchronization primitive that permits a certain number of count_down operations (decrements) before allowing one or more threads to pass the wait point. A latch cannot be reused once its internal counter reaches zero.

How do we use a latch?

  • A std::latch object is created with an initial count.
  • Multiple threads can decrement this count using the count_down method.
  • Threads can call wait, which block until the internal count of the latch reaches zero.

 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.