Home > front end >  Why does the main thread wait the thread created by std::async() if the return value is not hold by
Why does the main thread wait the thread created by std::async() if the return value is not hold by

Time:12-21

When I run the following code,

#include <thread>
#include <iostream>
#include <future>

int main() {
    auto fut = std::async(
        std::launch::async, 
        []{
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::cout << "sub : " << std::this_thread::get_id() << std::endl;
        }
    ); 

    std::cout << "do some on main thread" << std::endl;
    
    fut.get();

    std::cout << "main: " << std::this_thread::get_id() << std::endl;
}

I got the following output.

do some on main thread
sub : 139899103246080
main: 139899103250240

Running demo: https://godbolt.org/z/c9WedY4oq

It is the same behavior as I expected. "do some on main thread" outputs first, because the sub thread created by std::async() waits 1 second the beggining of the thread.

So far, so good.


However, when I removed the variable fut, then I got weird behavior for me. NOTE: This code is for only experimental purpose

#include <thread>
#include <iostream>
#include <future>

int main() {
    std::async(
        std::launch::async, 
        []{
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::cout << "sub : " << std::this_thread::get_id() << std::endl;
        }
    ); 

    std::cout << "do some on main thread" << std::endl;
    
    std::cout << "main: " << std::this_thread::get_id() << std::endl;
}

Here is the output:

sub : 139716056966912
do some on main thread
main: 139716056971072

Running demo: https://godbolt.org/z/obzzceGGr

It seems that the main thread waits until finishing the sub thread before outputing "do some on main thread".

I want to know why this behavior happens.

I got the warning message ":6:5: warning: ignoring return value of function declared with 'nodiscard' attribute [-Wunused-result]". Since C 20, the nodiscard attribute has been added. See https://en.cppreference.com/w/cpp/thread/async

I guess that I got an undefined behavior due to ignoring the return value of std::async(), but I couldn't find such document, so far.

CodePudding user response:

In the second case, a std::future object will still be created and returned.

That object is ephemeral and will be destructed immediately, and that leads to your problem because the std::future destructor will wait for the future to be ready before destruction continues.

  • Related