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