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 と同様ですが、同じ共有状態を複数のスレッドが待機することを可能とします。 ムーブのみ可能な (そのため任意の特定の非同期結果を参照できるのは1つのインスタンスに限られる) std::future と異なり、 std::shared_future はコピー可能であり、複数のオブジェクトで同じ共有状態を参照できます。
複数のスレッドからの同じ共有状態へのアクセスは、各々のスレッドが shared_future オブジェクトの個別のコピーを通して行う場合、安全です。
目次 |
[編集] メンバ関数
| フューチャーオブジェクトを構築します (パブリックメンバ関数) | |
| フューチャーオブジェクトを破棄します (パブリックメンバ関数) | |
| 内容を代入します (パブリックメンバ関数) | |
結果の取得 | |
| 結果を返します (パブリックメンバ関数) | |
状態 | |
| フューチャーが共有状態を持っているかどうか調べます (パブリックメンバ関数) | |
| 結果が利用可能になるのを待ちます (パブリックメンバ関数) | |
| 結果を待ちます。 指定されたタイムアウト期間が満了するまで利用可能にならなければリターンします (パブリックメンバ関数) | |
| 結果を待ちます。 指定時刻に達するまで利用可能にならなければリターンします (パブリックメンバ関数) | |
[編集] 例
std::condition_variable::notify_all() と同様に shared_future は複数のスレッドに同時に通知するために使うことができます
Run this code
#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 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

