Search code examples
multithreadingc++11stdasync

scope block when use std::async in function other than the main function


I have some problem with st::async when is use this in other function other than Main function, suppose, I have functions like flowing :

void printData() 
{
   for (size_t i = 0; i < 5; i++)
    {
        std::cout << "Test Function" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

void runningAsync()
{
    auto r = std::async(std::launch::async, test);
}

int main()
{
    runningAsync();

    std::cout << "Main Function" << std::endl;
}

the output of this code is :

Test Function
Test Function
Test Function
Test Function
Test Function
Main Function

that is not good, Main thread wait for other thread that be end.

I want runningAsync() function run in other thread and at the same time "Main Function" in main thread print on screan, this is possible with std::thread.

is that way for this running this functions an same time (concurrency)?


Solution

  • This QUESTION answered in :

    main thread waits for std::async to complete

    Can I use std::async without waiting for the future limitation?

    Whoever, If you store the std::future object, its lifetime will be extended to the end of main and you get the behavior you want.

    void printData() 
    {
       for (size_t i = 0; i < 5; i++)
        {
            std::cout << "Test Function" << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
    
    std::future<void> runningAsync()
    {
        return std::async(std::launch::async, test);
    }
    
    int main()
    {
        auto a = runningAsync();
    
        std::cout << "Main Function" << std::endl;
    }
    

    That's a problem because std::future's destructor may block and wait for the thread to finish. see this link for more details