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';
    }
相关推荐
Neteen23 分钟前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法
灰色小旋风1 小时前
力扣——第7题(C++)
c++·算法·leetcode
Java基基1 小时前
Spring让Java慢了30倍,JIT、AOT等让Java比Python快13倍,比C慢17%
java·开发语言·后端·spring
future02101 小时前
Spring AOP核心机制:代理与拦截揭秘
java·开发语言·spring·面试·aop
Ralph_Y1 小时前
C++网络:一
开发语言·网络·c++
Hui Baby2 小时前
浅谈MCP原理
开发语言
2345VOR2 小时前
【QT的pyside6开发使用】
开发语言·qt
程序猿编码2 小时前
探秘 SSL/TLS 服务密码套件检测:原理、实现与核心设计(C/C++代码实现)
c语言·网络·c++·ssl·密码套件
Ronin3052 小时前
【Qt常用控件】控件概述和QWidget 核心属性
开发语言·qt·常用控件·qwidget核心属性
故事和你912 小时前
sdut-程序设计基础Ⅰ-实验二选择结构(1-8)
大数据·开发语言·数据结构·c++·算法·优化·编译原理