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';
    }
相关推荐
阿童木写作3 分钟前
Python批量翻译亚马逊商品图实战教程
开发语言·python·xcode
会飞的大鱼人1 小时前
一文搞懂 Java HashSet:把它想成游乐园里只允许一次入场的盖章名单
java·开发语言·windows
ysa0510301 小时前
【板子】二分答案(最大最小?)
c++·笔记·算法·板子
jiay22 小时前
【.net10】顶级程序语句
java·开发语言
stolentime2 小时前
SP8549 MAIN75 - BST again题解
c++·算法·二叉树·深度优先·图论·记忆化搜索·组合数学
淼澄研学2 小时前
Python进阶实战:深入解析推导式与生成器等5大核心特性
开发语言·python
ziguo11222 小时前
C/C++ 错误处理全解:从 errno 到 C++ 异常
linux·c语言·c++·windows·visual studio
stolentime3 小时前
AT_pakencamp_2020_day1_k Gcd of Sum题解
c++·算法
2601_956121973 小时前
map_计蒜客T1271 完美K倍子数组
c++·算法
米码收割机3 小时前
【Python】Django 电子设备商城系统(源码+说明文档)[独一无二]
开发语言·python·django