std::barrier reset between arrive and wait

Viewed 60

I want to sync two threads and I found std::barrier.

Example:

There are 2 threads: (barrier is initialized by 2, call it expected count, and "expected count counts down" is abbreviated with "expected count down")

Thread1                               

while (true){                         
    barrier.arrive_and_wait();
    do_fast_work();
}
Thread2

while(true){
    barrier.arrive_and_wait();
    do_slow_work();
}

And run them:

Thread1.run();
this_thread::sleep(1s);
Thread2.run();

Thread1 runs, it arrives barrier, expected count down to 1, and wait.
Thread2 runs, it arrives barrier, expected count down to 0 and reset to 2, Thread1 stop waiting and countinues, expected count down to 1, and Thread2 wait.
Thread1 arrives barrier, expected count down to 0 and reset to 2, Thread2 stop waiting and continues, expected count down to 1, and Thread1 wait.

I expect Thread1 arrives barrier and wait, Thread2 arrives and wait, barrier resets and both thread stop waiting.

The problem is that arrive_and_wait is wait(arrive()). It resets before wait.

Is there any better resolution?

Edit: Detailed code:

using namespace std;
using namespace std::placeholders;

barrier<> mbarrier{2};

void do_fast_work(){
    this_thread::sleep(5s);
}

void do_slow_work(){
    this_thread::sleep(10s);
}

int main(){
    thread Thread1{
        []{
            while (true){                         
                mbarrier.arrive_and_wait();
                do_fast_work();
            }
        }
    };

    this_thread::sleep(1s);

    thread Thread2{
        []{
            while(true){
                mbarrier.arrive_and_wait();
                do_slow_work();
            }
        }
    }
    Thread1.join(); // wait forever
}
0 Answers
Related