std::future
From cppreference.com
| ヘッダ <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にリンクされている*共有状態*(例: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) | |
状態 (State) | |
| futureが共有状態を持っているかどうかをチェックします。 (public member function) | |
| 結果が利用可能になるまで待機します。 (public member function) | |
| 指定されたタイムアウト時間内に結果が利用可能でない場合、待機して戻ります。 (public member function) | |
| 指定された時刻までに結果が利用可能でない場合、待機して戻ります。 (public member function) | |
[編集] 例
このコードを実行
#include <future> #include <iostream> #include <thread> int main() { // future from a packaged_task std::packaged_task<int()> task([]{ return 7; }); // wrap the function std::future<int> f1 = task.get_future(); // get a future std::thread t(std::move(task)); // launch on a thread // future from an async() std::future<int> f2 = std::async(std::launch::async, []{ return 8; }); // future from a promise std::promise<int> p; std::future<int> f3 = p.get_future(); std::thread([&p]{ p.set_value_at_thread_exit(9); }).detach(); std::cout << "Waiting..." << std::flush; f1.wait(); f2.wait(); f3.wait(); std::cout << "Done!\nResults are: " << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n'; t.join(); }
出力
Waiting...Done! Results are: 7 8 9
[編集] 例外の例
このコードを実行
#include <future> #include <iostream> #include <thread> int main() { std::promise<int> p; std::future<int> f = p.get_future(); std::thread t([&p] { try { // code that may throw throw std::runtime_error("Example"); } catch (...) { try { // store anything thrown in the promise p.set_exception(std::current_exception()); } catch (...) {} // set_exception() may throw too } }); try { std::cout << f.get(); } catch (const std::exception& e) { std::cout << "Exception from the thread: " << e.what() << '\n'; } t.join(); }
出力
Exception from the thread: Example
[編集] 関連項目
| (C++11) |
関数を非同期で(潜在的に新しいスレッドで)実行し、結果を保持するstd::futureを返します。(関数テンプレート) |
| (C++11) |
非同期に設定される値(他のfutureから参照される可能性あり)を待機する (クラステンプレート) |