问题描述
我有以下非常简单的代码:
I have the following very simple code:
void TestSleep()
{
std::cout << "TestSleep " << std::endl;
sleep(10);
std::cout << "TestSleep Ok" << std::endl;
}
void TestAsync()
{
std::cout << "TestAsync" << std::endl;
std::async(std::launch::async, TestSleep);
std::cout << "TestAsync ok!!!" << std::endl;
}
int main()
{
TestAsync();
return 0;
}
因为我使用 std :: launch :: async
我希望 TestSleep()
将异步运行,并且我将获得以下输出:
Since I use std::launch::async
I expect that TestSleep()
will be run asynchronously and I will have the following output:
TestAsync
TestAsync ok!!!
TestSleep
TestSleep Ok
但实际上我有同步运行的输出:
But really I have the output for synchronous run:
TestAsync
TestSleep
TestSleep Ok
TestAsync ok!!!
您能否解释为什么以及如何制作 TestSleep
真的是异步调用。
Could you explain why and how to make TestSleep
call really asynchronously.
推荐答案
来自
From this std::async
reference notes section
如果从 std :: async
获得的 std :: future
从引用或绑定到引用, std :: future
的析构函数将在完整表达式的末尾阻塞,直到异步操作完成,从本质上使代码...同步
这就是这里发生的情况。由于您不存储 std :: async
返回的未来,因此它将在表达式末尾(即 std: :async
调用),它将阻塞直到线程结束。
This is what happens here. Since you don't store the future that std::async
returns, it will be destructed at the end of the expression (which is the std::async
call) and that will block until the thread finishes.
如果您这样做,例如
auto f = std::async(...);
然后销毁 f
TestAsync
的行将被阻止,并且文本 TestAsync ok !!!
应该在 TestSleep OK 。
then the destruction of f
at the end of TestAsync
will block, and the text "TestAsync ok!!!"
should be printed before "TestSleep Ok"
.
这篇关于std :: async无法异步工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!