0

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)?

2 Answers2

3

The reason is that std::async returns a std::future which you store in an auto variable. As soon as your future runs out of scope (at the end of runningAsync()!), its destructor blocks until the task is finished. If you do not want that, you could for example store the future in a global container.

Benjamin Bihler
  • 1,612
  • 11
  • 32
1

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

Jack D
  • 249
  • 1
  • 12
  • Source won't compile as it is. Change either `test` with `printData` or vice versa. – marc Jan 22 '20 at 10:55