名前空間
変種
操作

std::shared_future

提供: cppreference.com
< cpp‎ | thread
 
 
スレッドサポートライブラリ
スレッド
(C++11)
(C++20)
(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++11)
セマフォ
ラッチとバリア
(C++20)
(C++20)
フューチャー
(C++11)
(C++11)
shared_future
(C++11)
(C++11)
 
 
ヘッダ <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 と同様ですが、同じ共有状態を複数のスレッドが待機することを可能とします。 ムーブのみ可能な (そのため任意の特定の非同期結果を参照できるのは1つのインスタンスに限られる) std::future と異なり、 std::shared_future はコピー可能であり、複数のオブジェクトで同じ共有状態を参照できます。

複数のスレッドからの同じ共有状態へのアクセスは、各々のスレッドが shared_future オブジェクトの個別のコピーを通して行うならば、安全です。

目次

[編集]メンバ関数

フューチャーオブジェクトを構築します
(パブリックメンバ関数)[edit]
フューチャーオブジェクトを破棄します
(パブリックメンバ関数)
内容を代入します
(パブリックメンバ関数)
結果の取得
結果を返します
(パブリックメンバ関数)[edit]
状態
フューチャーが共有状態を持っているかどうか調べます
(パブリックメンバ関数)[edit]
結果が利用可能になるのを待ちます
(パブリックメンバ関数)[edit]
結果を待ちます。 指定されたタイムアウト期間が満了するまで利用可能にならなければリターンします
(パブリックメンバ関数)[edit]
結果を待ちます。 指定時刻に達するまで利用可能にならなければリターンします
(パブリックメンバ関数)[edit]

[編集]

std::condition_variable::notify_all() と同様に shared_future は複数のスレッドに同時に通知するために使うことができます

#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();// メインからの通知を待ちます。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();// メインからの通知を待ちます。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);   // スレッドが準備できるまで待ちます。 fut1.wait(); fut2.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
close