在线文档教程
C++
线程支持 | Thread support

std::shared_future

STD::共享[医]未来

Defined in header
template< class T > class shared_future;(1)(since C++11)
template< class T > class shared_future<T&>;(2)(since C++11)
template<> class shared_future<void>;(3)(since C++11)

类模板std::shared_future提供访问异步操作结果的机制,类似于std::future,只是允许多个线程等待相同的共享状态。不像std::future,因此只有一个实例可以引用任何特定的异步结果%29,std::shared_future是可复制的,多个共享的未来对象可能引用相同的共享状态。

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

成员函数

(constructor)constructs the future object (public member function)
(destructor)destructs the future object (public member function)
operator=assigns the contents (public member function)

得到结果

GET返回结果%28公共成员函数%29

国家

有效检查未来是否具有共享状态%28公共成员函数%29

等待结果变为可用%28公共成员函数%29

等待[医]对于等待结果,如果指定的超时持续时间%28公共成员函数%29不可用,则返回

等待[医]在等待结果之前,如果指定的时间点已达到%28公共成员函数%29,则返回不可用的结果。

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( // 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 result1 = std::async(std::launch::async, fun1 auto result2 = std::async(std::launch::async, fun2 // wait for the threads to become ready t1_ready_promise.get_future().wait( t2_ready_promise.get_future().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

二次

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/线程/Shared[医]未来