Open In App

std::barrier in C++20

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The std::barrier class is a new synchronization primitive introduced in C++20 that facilitates the synchronization of multiple threads working on a common task. It operates as a barrier that all threads must reach before the program can continue. Although the std::barrier object is similar to the std::mutex or std::condition_variable, there are some significant differences that make it unique.

How does std::barrier work?

Upon creating a std::barrier object, the number of participating threads must be specified. Each thread participating in the barrier uses the std::barrier::arrive_and_wait() function when it reaches the barrier. The std::barrier object monitors how many threads have arrived at the barrier. When all threads have reached the barrier, the barrier is lifted, and all threads can resume execution.

The std::barrier class sets itself apart from other synchronization primitives by allowing users to specify a callback function that executes after the barrier is lifted. This callback function can perform additional tasks that must be completed after the barrier has been crossed. This feature enhances the flexibility and versatility of the std::barrier class, making it a useful tool for multi-threaded programming in C++20.

Example:

C++




// C++ Program to demonstrate use of use std::barrier in
#include <barrier>
#include <iostream>
#include <thread>
  
std::barrier my_barrier{ 3 };
  
void my_function()
{
    my_barrier.arrive_and_wait();
}
  
int main()
{
  
    // creating threads
    std::thread t1(my_function);
    std::thread t2(my_function);
    std::thread t3(my_function);
  
    t1.join();
    t2.join();
    t3.join();
  
    std::cout << "All threads have finished\n";
  
    return 0;
}


Output:

All threads have finished

Explanation of the above program:

In this example, we demonstrate how to use the std::barrier class to synchronize multiple threads working on a common task. We create an instance of the std::barrier class, named my_barrier, with a count of 3. Three threads are created that call my_function(). At the barrier, each thread calls my_barrier.arrive_and_wait() to halt execution until all other threads have reached the barrier. Once all threads have arrived, the barrier is lifted, and all threads are released to resume execution. Upon finishing, the console displays the message “All threads have finished.”.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads