命名空间
变体
操作

std::shared_future

来自 cppreference.cn
< cpp‎ | thread
 
 
并发支持库
线程
(C++11)
(C++20)
this_thread 命名空间
(C++11)
(C++11)
(C++11)
协同取消
互斥
(C++11)
通用锁管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
条件变量
(C++11)
信号量
门闩和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
shared_future
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危险指针
原子类型
(C++11)
(C++20)
原子类型的初始化
(C++11)(C++20 中已弃用)
(C++11)(C++20 中已弃用)
内存排序
(C++11)(C++26 中已弃用)
原子操作的自由函数
原子标志的自由函数
 
 
在头文件 <future> 中定义
template< class T > class shared_future;
(1) (C++11 起)
template< class T > class shared_future<T&>;
(2) (C++11 起)
template<> class shared_future<void>;
(3) (C++11 起)

类模板 std::shared_future 提供了一种访问异步操作结果的机制,类似于 std::future,不同之处在于允许多个线程等待相同的共享状态。与 std::future(只能移动,因此只有一个实例可以引用任何特定的异步结果)不同,std::shared_future 可复制,并且多个共享 future 对象可以引用相同的共享状态。

如果每个线程都通过其自己的 shared_future 对象副本访问相同的共享状态,则从多个线程访问共享状态是安全的。

目录

[编辑] 成员函数

构造 future 对象
(公共成员函数) [编辑]
析构 future 对象
(公开成员函数)
赋值内容
(公开成员函数)
获取结果
返回结果
(公共成员函数) [编辑]
状态
检查 future 是否具有共享状态
(公共成员函数) [编辑]
等待结果可用
(公共成员函数) [编辑]
等待结果,如果在指定的超时时间内不可用则返回
(公共成员函数) [编辑]
等待结果,如果到指定时间点仍不可用则返回
(公共成员函数) [编辑]

[编辑] 示例

shared_future 可用于同时唤醒多个线程,类似于 std::condition_variable::notify_all()

#include <chrono>
#include <future>
#include <iostream>
 
int main()
{   
    std::promise<void> ready_promise, t1_ready_promise, t2_ready_promise;
    std::shared_future<void> ready_future(ready_promise.get_future());
 
    std::chrono::time_point<std::chrono::high_resolution_clock> start;
 
    auto fun1 = [&, ready_future]() -> std::chrono::duration<double, std::milli> 
    {
        t1_ready_promise.set_value();
        ready_future.wait(); // waits for the signal from main()
        return std::chrono::high_resolution_clock::now() - start;
    };
 
 
    auto fun2 = [&, ready_future]() -> std::chrono::duration<double, std::milli> 
    {
        t2_ready_promise.set_value();
        ready_future.wait(); // waits for the signal from main()
        return std::chrono::high_resolution_clock::now() - start;
    };
 
    auto fut1 = t1_ready_promise.get_future();
    auto fut2 = t2_ready_promise.get_future();
 
    auto result1 = std::async(std::launch::async, fun1);
    auto result2 = std::async(std::launch::async, fun2);
 
    // wait for the threads to become ready
    fut1.wait();
    fut2.wait();
 
    // the threads are ready, start the clock
    start = std::chrono::high_resolution_clock::now();
 
    // signal the threads to go
    ready_promise.set_value();
 
    std::cout << "Thread 1 received the signal "
              << result1.get().count() << " ms after start\n"
              << "Thread 2 received the signal "
              << result2.get().count() << " ms after start\n";
}

可能的输出

Thread 1 received the signal 0.072 ms after start
Thread 2 received the signal 0.041 ms after start

[编辑] 参阅

(C++11)
异步(可能在新线程中)运行一个函数并返回一个将保存结果的 std::future
(函数模板) [编辑]
(C++11)
等待一个异步设置的值
(类模板) [编辑]