std:: future
From cppreference.net
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::future
| Member functions | ||||
| Getting the result | ||||
| State | ||||
|
ヘッダーで定義
<future>
|
||
|
template
<
class
T
>
class
future
;
|
(1) | (C++11以降) |
|
template
<
class
T
>
class
future
<
T
&
>
;
|
(2) | (C++11以降) |
|
template
<>
class
future
<
void
>
;
|
(3) | (C++11以降) |
クラステンプレート
std::future
は、非同期操作の結果にアクセスするための仕組みを提供します:
-
非同期操作(
std::async
、
std::packaged_task
または
std::promise
によって作成されたもの)は、その非同期操作の作成者に
std::futureオブジェクトを提供することができます。
-
非同期操作の作成者は、その後、様々な方法を使用して
std::futureから値を問い合わせ、待機、または抽出することができます。これらのメソッドは、非同期操作がまだ値を提供していない場合にブロックする可能性があります。
-
非同期操作が作成者に結果を送信する準備ができたとき、作成者の
std::futureにリンクされている shared state (例: std::promise::set_value )を変更することで送信できます。
std::future
が参照する共有状態は、他の非同期戻り値オブジェクトと共有されないことに注意してください(これは
std::shared_future
とは対照的です)。
目次 |
、
、
メンバー関数
|
futureオブジェクトを構築する
(public member function) |
|
|
futureオブジェクトを破棄する
(public member function) |
|
|
futureオブジェクトを移動する
(public member function) |
|
|
共有状態を
*
this
から
shared_future
に転送して返す
(public member function) |
|
結果の取得 |
|
|
結果を返す
(public member function) |
|
状態 |
|
|
futureが共有状態を持っているかチェックする
(public member function) |
|
|
結果が利用可能になるまで待機する
(public member function) |
|
|
結果を待機し、指定されたタイムアウト期間内に利用できない場合は返る
(public member function) |
|
|
結果を待機し、指定された時点までに利用できない場合は返る
(public member function) |
|
例
このコードを実行
#include <future> #include <iostream> #include <thread> int main() { // packaged_taskからのfuture std::packaged_task<int()> task([]{ return 7; }); // 関数をラップ std::future<int> f1 = task.get_future(); // futureを取得 std::thread t(std::move(task)); // スレッドで起動 // async()からのfuture std::future<int> f2 = std::async(std::launch::async, []{ return 8; }); // promiseからのfuture <span class="
例外を伴う例
このコードを実行
#include <future> #include <iostream> #include <thread> int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t([&p] { try { // 例外をスローする可能性のあるコード throw std::runtime_error("Example"); } catch (...) { try { // promiseにスローされた例外を保存 p.set_exception(std::current_exception()); } catch (...) {} // set_exception()も例外をスローする可能性あり } }); try { std::cout << f.get(); } catch (const std::exception& e) { std::cout << "スレッドからの例外: " << e.what() << '\n'; } t.join(); }
出力:
Exception from the thread: Example
関連項目
|
(C++11)
|
関数を非同期で(場合によっては新しいスレッドで)実行し、結果を保持する
std::future
を返す
(関数テンプレート) |
|
(C++11)
|
非同期に設定される値(他のfuturesによって参照される可能性がある)を待機する
(クラステンプレート) |