示例说明

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

  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;
}
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐