C++ barrier::max() Function



The std::barrier::max() function in C++, is used to return the maximum count value of the barrier object that can support. A barrier is a synchronization tool used to manage multiple threads by ensuring they reach a specific point before proceeding further. This function provides an upper limit on the count of the threads a barrier can synchronize at once.

Syntax

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

static constexpr std::ptrdiff_t max() noexcept;

Parameters

It does not accepts any parameter.

Return value

This function returns the maximum value of the expected count supported by the implementation.

Example 1

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

#include <iostream>
#include <barrier>
int main() {
   std::barrier a(2);
   std::cout << "Result : " << a.max() << std::endl;
   return 0;
}

Output

Output of the above code is as follows −

Result : 9223372036854775807

Example 2

Consider the following example, we are going to use the max() with multiple threads and displays the maximum count.

#include <iostream>
#include <barrier>
#include <thread>
void a(std::barrier < > & b) {
   std::cout << "Thread ID " << std::this_thread::get_id() <<
      " Max_count : " << b.max() << std::endl;
}
int main() {
   std::barrier b(2);
   std::thread x1(a, std::ref(b));
   std::thread x2(a, std::ref(b));
   x1.join();
   x2.join();
   return 0;
}

Output

Following is the output of the above code −

Thread ID 124977672095296 Max_count : 9223372036854775807
Thread ID 124977682581056 Max_count : 9223372036854775807
cpp_barrier.htm