1、问题描述
直接调用std::async,出现不异步执行问题,使用以下代码,简单的测试std::async执行情况
#include <iostream>
#include <future>
using namespace std;
int main()
{
cout << "test async begin" << endl;
async(launch::async, []()
{
std::cout << "start" << std::endl;
Sleep(200);
std::cout << "end" << std::endl;
});
cout << "test async finish" << endl;
system("pause");
return 0;
}
预期的结果是这样的:
test async begin
test async finish
start
end
但执行后的结果:
test async begin
start
end
test async finish
2、解决问题
为std::async添加返回值以后,得到期望的结果,更改后如下:
future<void> future = async(launch::async, []()
{
std::cout << "start" << std::endl;
Sleep(200);
std::cout << "end" << std::endl;
});
3、问题分析
通过查看std::async参考注释部分发现:
If the
std::future
obtained fromstd::async
is not moved from or bound to a reference, the destructor of thestd::future
will block at the end of the full expression until theasynchronous operation completes, essentially making code ... synchronous
由于刚开始没有存储std::async返回值,它将在表达式(即std::async调用)的末尾被销毁,并将阻塞直到线程结束。在添加返回值后,std::async调用后立即返回,在std::async调用结束前返回值的销毁将被阻止,有点类似如下代码:
std::thread execute([this]()
{
dosomething();
});
execute.detach();//分离,驻留后台