c++multithreadingpthreadsc++14std-call-once

Thread Join hangs while using `std::call_once`


I am trying to understand why std::call_once and std::once_flag My program

#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>

using namespace std;
once_flag once;


void test(int i){
    if(i==1){
        cout<<"will be called again"<<endl;
        throw exception();
    }
    cout<<"wont be called again"<<endl;
}

void caller(int i){
    try{
        call_once(once, test, i);
    }catch(...){cout<<"caught"<<endl;}
}

int main(){
    int val = 1;
    thread t1(caller,1);
    thread t2(caller,2);
    thread t3(caller,2);
    t1.join();t2.join();t3.join();
}

terminal output : 1 will be called again\n caught\n wont be called again\n and this just hangs , sometimes it get finished but most of the time it hangs, I think its race condtion but cant figure out why is it haappening. I found the same example here https://en.cppreference.com/w/cpp/thread/call_once


Solution

  • It seems that this is a bug in gcc (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66146).

    You can reproduce the issue by inserting a short sleep after constructing t1 in your example, e.g.

    std::thread t1(caller,1);
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(1ms);