名稱空間
變體
操作

std::shared_future

來自 cppreference.com
< 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)
危險指標
原子型別
(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)
等待一個非同步設定的值
(類模板) [編輯]