October 17, 20241 yr In 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. â¬Ã¡ View the full article
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.