std:: shared_future
From cppreference.net
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::shared_future
| Member functions | ||||
| Getting the result | ||||
| State | ||||
|
ヘッダーで定義
<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
はコピー可能であり、複数のshared futureオブジェクトが同じ共有状態を参照できます。
複数のスレッドから同じ共有状態にアクセスする場合、各スレッドが自身の
shared_future
オブジェクトのコピーを通じて行うのであれば、これは安全です。
目次 |
メンバー関数
|
futureオブジェクトを構築する
(public member function) |
|
|
futureオブジェクトを破棄する
(public member function) |
|
|
内容を代入する
(public member function) |
|
結果の取得 |
|
|
結果を返す
(public member function) |
|
状態 |
|
|
futureが共有状態を持っているかチェックする
(public member function) |
|
|
結果が利用可能になるまで待機する
(public member function) |
|
|
結果を待機し、指定されたタイムアウト期間内に利用できない場合は返る
(public member function) |
|
|
結果を待機し、指定された時間ポイントに達するまで利用できない場合は返る
(public member function) |
|
例
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::<span class
関連項目
|
(C++11)
|
関数を非同期で(場合によっては新しいスレッドで)実行し、結果を保持する
std::future
を返す
(関数テンプレート) |
|
(C++11)
|
非同期に設定される値を待機する
(クラステンプレート) |