lundi 8 juillet 2019

Is a future safe to pass to a detached thread?

Is passing a std::future to a detached instance of std::thread a safe operation? I know that underneath, the std::future has state in a shared_ptr which it shares with a std::promise. Here is an example.

int main()
{
    std::promise<void> p;
    std::thread t( [f = p.get_future()] {
        if ( f.wait_for( std::chrono::seconds( 2 ) ) == std::future_status_ready ) 
        {
            return;
        }

        std::terminate();
    } )
        .detach();

    // wait for some operation

    p.set_value();
}

There is a potential error case in the above code where the lambda is executed after the main thread exits. Does the shared state remain after the main thread exits?

Aucun commentaire:

Enregistrer un commentaire