Barriers and latches
In this section, we will introduce barriers and latches, two new synchronization primitives introduced in C++20. These mechanisms allow threads to wait for each other, thereby coordinating the execution of concurrent tasks.
std::latch
The std::latch
latch is a synchronization primitive that allows one or more threads to block until a specified number of operations are completed. It is a single-use object, and once the count reaches zero, it cannot be reset.
The following example is a simple illustration of the use of latches in a multithreaded application. We want to write a function to multiply by two each element of a vector and then add all the elements of the vector. We will use three threads to multiply the vector elements by two and then one thread to add all the elements of the vector and obtain the result.
We need two latches. The first one will be decremented by each of the three threads multiplying by two vector elements. The adding thread...