Namespaces
Variants

std:: shared_future

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
shared_future
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
定义于头文件 <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)
等待异步设置的值
(类模板)