我有以下代码:
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
using namespace std;
int sleep_10s()
{
this_thread::sleep_for(chrono::seconds(10));
cout << "Sleeping Done\n";
return 3;
}
int main()
{
auto result=async(launch::async, sleep_10s);
auto status=result.wait_for(chrono::seconds(1));
if (status==future_status::ready)
cout << "Success" << result.get() << "\n";
else
cout << "Timeout\n";
}
这应该等待 1 秒,打印“Timeout”,然后退出。它没有退出,而是额外等待 9 秒,打印“Sleeping Done”,然后出现段错误。有没有办法取消或分离未来,以便我的代码将在 main 末尾退出,而不是等待未来完成执行?
C++11 标准没有提供直接的方法来取消以std::async
。您必须实现自己的取消机制,例如将原子标志变量传递给定期检查的异步任务。
不过你的代码不应该崩溃。到达终点时main
, the std::future<int>
物体被夹在result
被销毁,它将等待任务完成,然后丢弃结果,清理所有使用的资源。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)