0

Consider following examples:

1. All functions are called asynchronously

void threadFunc()
{
    while (1)
    {
        std::cout << "thread working..\n";
        std::this_thread::sleep_for(1s);
    }
}

void middleFunc()
{
    std::async(std::launch::async, threadFunc);
    std::cout << "humble\n";
}

int main()
{
    std::async(std::launch::async, middleFunc); // this special line
    while (1)
    {
        std::cout << "main working..\n";
        std::this_thread::sleep_for(1s);
    }
}

Everything works fine and output comes as

main working..
humble
other working..
main working..
other working..
main working..

2. First function is called synchronously, and second is called asynchronously

if I replace async call in main with a normal function call, like so:

int main()
{
    middleFunc(); // this special line
    while (1)
    {
        std::cout << "main working..\n";
        std::this_thread::sleep_for(1s);
    }
}

then only middleFunc() & threadFunc() run, execution never reaches main()'s while loop, and output comes as

humble
other working..
other working..
other working..
other working..

In both the cases threadFunc() runs with std::async. So, as soon as middleFunc() prints 'humble' shouldn't it return back to main() ?

  • `async` isn't as asynchronous as you may think it is: https://stackoverflow.com/questions/36816928/why-c-async-run-sequentially-without-future – hlt May 10 '18 at 18:03
  • 1
    If you don't do something with the `std::future` that's returned by `std::async` then the call will block until the future's destructor finishes, which requires that the function called by `async` finishes. Save your `std::future`. – François Andrieux May 10 '18 at 18:07
  • thanks @hlt and @François Andrieux I added a global variable `std::future globalFuture;` , which is getting the future returned by `middleFunc()` 's `std::async`. Now everything works asynchronously. – anuragyayhdapu May 11 '18 at 13:46

0 Answers0