请考虑以下示例:
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);
}
}
然后只有midFunc()&amp; threadFunc()运行,执行永远不会到达main()循环,输出为
humble
other working..
other working..
other working..
other working..
在两种情况下,threadFunc()都使用std :: async运行。所以,只要middleFunc()打印出“谦逊”的声音,它不应该返回main()吗?