c++barrier

How to use C++ std::barrier arrival_token?


I keep getting a compiler error when using the std::barrier arrive and wait functions separately.

I've been trying to find examples of using these functions but I can't find them so I'm just shooting wild at this point.

It complaines that my arrival token is not an rvalue, so I changed the declaration to use &&, but I'm not that familiar with how rvalues work.

Here's the code:

void thread_fn(std::barrier<>& sync_point)
{
    /* Do 1st task... */

    std::barrier<>::arrival_token&& arrival = sync_point.arrive();

    /* Do 2nd task... */

    /* Wait for everyone to finish 1st task */
    sync_point.wait(arrival);

    /* Do 3rd task... */
}

I get the compile error:

test.cpp: In function ‘void thread_fn(std::barrier<>&)’:
test.cpp:12:21: error: cannot bind rvalue reference of type ‘std::barrier<>::arrival_token&&’ to lvalue of type ‘std::barrier<>::arrival_token’
   12 |     sync_point.wait(arrival);
      |                     ^~~~~~~

Solution

  • A variable with an rvalue reference type is an lvalue (arrival is an lvalue).

    std::barrier<>::wait takes an arrival_token&&, so you need to move from the lvalue:

    sync_point.wait(std::move(arrival));