Synchronizing threads with latches, barriers, and semaphores
The thread support library from C++11 includes mutexes and condition variables that enable thread-synchronization to shared resources. A mutex allows only one thread of multiple processes to execute, while other threads that want to access a shared resource are put to sleep. Mutexes can be expensive to use in some scenarios. For this reason, the C++20 standard features several new, simpler synchronization mechanisms: latches, barriers, and semaphores. Although these do not provide new use cases, they are simpler to use and can be more performant because they may internally rely on lock-free mechanisms.
Getting ready
The new C++20 synchronization mechanisms are defined in new headers. You have to include <latch>
for std::latch
, <barrier>
, or std::barrier
, and <semaphore>
for std::counting_semaphore
and std::binary_semaphore
.
The code snippets in this recipe will use the following two functions...