示例说明
示例很简单,大致步骤为:
- 调用异步函数async创建异步对象,返回结果为future类型
- 合适的时候使用异步对象返回的future方法检测异步任务执行进度
- 检测任务执行成功后,使用future的get方法获取异步任务执行结果
代码示例:
#include <future>
#include <iostream>
#include <string>
std::string DoTimeCostWork(int nId)
{
for (int i = 1; i<nId; i++)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return "包子三斤四两";
}
int main()
{
std::future<std::string> fut = std::async(DoTimeCostWork, 16);
// 每100毫秒轮询查看任务执行进度
std::chrono::milliseconds tSpan(100);
while (fut.wait_for(tSpan) != std::future_status::ready)
{
std::cout << "客观别急,任务还没完" << std::endl;
}
// 获取执行结果
std::cout << "\n异步任务执行完毕:" << fut.get() << std::endl;
return 0;
}