C++11 异步编程示例-future

示例说明

示例很简单,大致步骤为:

  1. 调用异步函数async创建异步对象,返回结果为future类型
  2. 合适的时候使用异步对象返回的future方法检测异步任务执行进度
  3. 检测任务执行成功后,使用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;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值