C++20 Concurrency: std::barrier
I previously wrote about using std::latch
to synchronize multiple threads. While that is a great mechanism for simple one-time synchronization scenarios where multiple threads need to meet at a synchronization point before continuing execution, it is less flexible than the other new C++20 concurrency primitive: std::barrier
.
What is std::barrier
?
Like std::latch
, std::barrier
is a synchronization mechanism that allows a fixed number of threads to synchronize at a certain point in their execution. However, there are a few key differences:
std::barrier
is reusable: Whilestd::latch
can only be used one time (once the down-counter reaches 0, it becomes unusable),std::barrier
can be reused multiple times. Once all threads have reached the sync point, the barrier resets for the next iteration.std::barrier
has a callback function: After the sync point is reached by all threads, thestd::barrier
executes a potentially empty callback function.- Slightly different “wait” behavior:
std::latch
usescount_down()
to decrement its counter andwait()
to block until the counter reaches 0, whilestd::barrier
typically usesarrive_and_wait()
to both decrement the counter and block. It is possible to do these steps independently (arrive()
thenwait()
) if desired.
Below is the example that I used previously for std::latch
: