c++ future 使用详解

c++ future 使用详解

std::future

  • 头文件 #include <future>

  • 类模板,定义如下:

    cpp 复制代码
    template<class T> class future;
    template<class T> class future<T&>;
    template<>        class future<void>;
  • 作用:提供了一种机制,可以获取异步任务的执行结果、等待异步任务的完成、检查异步任务的状态等操作。

  • 使用:通常情况下,与 std::async,std::promise 和 std::packaged_task 结合使用。

std::future 成员函数

  • get:获取任务的执行结果;
  • wait:等待结果变得可用;
  • wait_for:等待结果,如果在指定的超时间隔后仍然无法得到结果,则返回;
  • wait_until:等待结果,如果在已经到达指定的时间点时仍然无法得到结果,则返回。

wait_for wait_until

  • 函数原型:

    cpp 复制代码
    template<class Rep, class Period>
    std::future_status wait_for(const std::chrono::duration<Rep,Period>& timeout_duration) const;
    
    template<class Clock, class Duration>
    std::future_status wait_until( const std::chrono::time_point<Clock,Duration>& timeout_time) const;
    • timeout_duration:要阻塞的最大时长。
    • timeout_time:要阻塞到的最大时间点。
    • 返回值:std::future_status:
      • future_status::deferred:函数被延迟运行,结果将仅在调用 wait 或者 get 时进行计算;
      • future_status::ready:结果已经就绪;
      • future_status::timeout:结果经过指定的等待时间后仍未就绪;
  • 推荐使用稳定时钟,避免因系统时间调整而受到影响。

示例代码

  • 与 std::async,std::promise 和 std::packaged_task 的结合使用:

    cpp 复制代码
    #include <iostream>
    #include <future>
    #include <thread>
    
    int main()
    {
        // 来自 packaged_task 的 future
        std::packaged_task<int()> task([]() { return 100; });
        // 获取 future
        std::future<int> f1 = task.get_future();
        // 在线程上运行
        std::thread(std::move(task)).detach();
    
        // 来自 async 的 future
        std::future<int> f2 = std::async(std::launch::async, []() { return 200; });
    
        // 来自 promise 的 future
        std::promise<int> p;
        std::future<int> f3 = p.get_future();
        std::thread([&p] { p.set_value_at_thread_exit(300); }).detach();
    
        std::cout << "Waiting..." << std::flush;
        f1.wait();
        f2.wait();
        f3.wait();
        std::cout << "Done!\nResults are: ";
        std::cout << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
    }
相关推荐
才鲸嵌入式1 小时前
C++相比于C语言增加了哪些概念?
c语言·c++·单片机·嵌入式·arm·面向对象·软件
周圣贤2 小时前
九尾狐编程语言新算法“超维时空演算体”
开发语言·算法
CaracalTiger3 小时前
HTTP 协议的基本概念(请求/响应流程、状态码、Header、方法)问题解决方案大全
开发语言·网络·python·深度学习·网络协议·http·pip
随缘而动,随遇而安3 小时前
第八十二篇 大数据开发基础:树形数据结构深度解析与实战指南(附创新生活案例)
大数据·开发语言·数据结构
西猫雷婶3 小时前
python学智能算法(十三)|机器学习朴素贝叶斯方法进阶-简单二元分类
开发语言·人工智能·python·深度学习·机器学习·矩阵·分类
武子康4 小时前
Java-49 深入浅出 Tomcat 手写 Tomcat 实现【02】HttpServlet Request RequestProcessor
java·开发语言·后端·学习·spring cloud·tomcat
张朝阳的博客4 小时前
哈夫曼树Python实现
开发语言·python
阑梦清川4 小时前
C#建立与数据库连接(版本问题的解决方案)踩坑总结
开发语言·数据库·c#
听风lighting5 小时前
1. C++ WebServer项目分享
linux·c语言·c++·设计模式·嵌入式·webserver
药9555 小时前
数据结构 4 (栈和队列)
java·开发语言·数据结构