考虑以下示例:
1.所有函数都是异步调用的
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);
}
}
一切正常,输出如下
main working..
humble
other working..
main working..
other working..
main working..
2.第一个函数被同步调用,第二个被异步调用
如果我用普通函数调用替换 main 中的异步调用,如下所示:
int main()
{
middleFunc(); // this special line
while (1)
{
std::cout << "main working..\n";
std::this_thread::sleep_for(1s);
}
}
然后只有 middleFunc() & threadFunc() 运行,执行永远不会到达 main() 的 while 循环,输出为
humble
other working..
other working..
other working..
other working..
在这两种情况下,threadFunc() 都使用 std::async 运行。那么,一旦 middleFunc() 打印出 'humble' ,它不应该返回 main() 吗?