C++ barrier::wait() Function



The std::barrier::wait() function in C++, is a synchronization mechanism introduced in C++20 that pauses a thread until the required number of threads reach the barrier.

A barrier holds a fixed number of threads, allowing each thread to perform work until they reach a common point. once all the threads have reached this point, the barrier is released and each thread continues execution.

Syntax

Following is the syntax for std::barrier::wait() function.

 void wait( arrival_token&& arrival ) const; 

Parameters

  • arrival − It indicates an arrival_token obtained by a previous call to arrive on the same barrier.

Return value

This function does not returns anything.

Exception

It throws std::system_error with an error code allowed for mutex types on error.

Example 1

In the following example, we are going to consider the basic usage of the wait() function.

 #include <iostream> #include <thread> #include <barrier> void a(std::barrier < > & y, int b) { std::cout << "Thread working.\n"; std::this_thread::sleep_for(std::chrono::milliseconds(100 * b)); std::cout << "Thread reached barrier.\n"; y.arrive_and_wait(); std::cout << "Thread passed the barrier.\n"; } int main() { std::barrier y(1); std::thread x1(a, std::ref(y), 1); x1.join(); return 0; } 

Output

Output of the above code is as follows −

 Thread working. Thread reached barrier. Thread passed the barrier. 
cpp_barrier.htm
Advertisements