std::shared_future
來自 cppreference.com
在標頭檔案 <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) |
等待一個非同步設定的值 (類模板) |