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';
    }
相关推荐
wjs20242 小时前
Django Nginx+uWSGI 安装配置指南
开发语言
七夜zippoe3 小时前
JVM类加载机制(Class Loading)详解:双亲委派模型与破坏实践
java·开发语言·jvm·类加载·双亲委派
曹牧3 小时前
C#:无法从方法组转换为objec
开发语言·c#
自动化代码美学3 小时前
【Python3.13】官网学习之控制流
开发语言·windows·python·学习
AA陈超4 小时前
ASC学习笔记0020:用于定义角色或Actor的默认属性值
c++·笔记·学习·ue5·虚幻引擎
coderxiaohan5 小时前
【C++】仿函数 + 模板进阶
开发语言·c++
IMPYLH6 小时前
Lua 的 collectgarbage 函数
开发语言·笔记·junit·单元测试·lua
百锦再6 小时前
第18章 高级特征
android·java·开发语言·后端·python·rust·django
Tony Bai6 小时前
Go 在 Web3 的统治力:2025 年架构与生态综述
开发语言·后端·架构·golang·web3