std::shared_future

定义于头文件 <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 可复制而且多个 shared_future 对象能指代同一共享状态。

若每个线程通过其自身的 shared_future 对象副本访问,则从多个线程访问同一共享状态是安全的。

目录

成员函数

构造期货对象
(公开成员函数)
销毁期货对象
(公开成员函数)
赋值内容
(公开成员函数)
获取结果
返回结果
(公开成员函数)
状态
检查 future 是否拥有共享状态
(公开成员函数)
等待结果变得可用
(公开成员函数)
等待结果,如果在指定的超时间隔后仍然无法得到结果,则返回。
(公开成员函数)
等待结果,如果在已经到达指定的时间点时仍然无法得到结果,则返回。
(公开成员函数)

示例

shared_future 可用于同时向多个线程发信,类似 std::condition_variable::notify_all()

#include <iostream>
#include <future>
#include <chrono>
 
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(); // 等待来自 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(); // 等待来自 main() 的信号
        return std::chrono::high_resolution_clock::now() - start;
    };
 
    auto result1 = std::async(std::launch::async, fun1);
    auto result2 = std::async(std::launch::async, fun2);
 
    // 等待线程变为就绪
    t1_ready_promise.get_future().wait();
    t2_ready_promise.get_future().wait();
 
    // 线程已就绪,开始时钟
    start = std::chrono::high_resolution_clock::now();
 
    // 向线程发信使之运行
    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

版本历史

  • (当前 | 先前 2017年9月25日 (一) 00:09Fruderica讨论 | 贡献 . . (3,185字节) (0). . (wording) (撤销)
  • 当前 | 先前 2017年9月24日 (日) 08:30Fruderica讨论 | 贡献. . (3,185字节) (+1,750). . (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:34P12bot讨论 | 贡献 . . (1,435字节) (-206). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 18:47P12bot讨论 | 贡献 . . (1,641字节) (+257). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:32P12讨论 | 贡献 . . (1,384字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,384字节) (+1,384). . (Translated from the English version using Google Translate)