命名空间
变体
操作

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)
Hazard 指针
原子类型
(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)
等待异步设置的值
(类模板) [编辑]