std::promise<R>::set_exception
From cppreference.com
| void set_exception( std::exception_ptr p ); |
(C++11以降) | |
アトミックに、共有状態に例外ポインタ p を格納し、状態を準備完了にします。
この操作は、set_value、set_exception、set_value_at_thread_exit、および set_exception_at_thread_exit が、プロミスオブジェクトを更新する間に、プロミスオブジェクトに関連付けられた単一のミューテックスを取得するかのように動作します。
共有状態が存在しない場合、または共有状態に既に値または例外が格納されている場合は、例外がスローされます。
この関数への呼び出しは、get_future への呼び出しとのデータ競合を発生させません(したがって、互いに同期する必要はありません)。
目次 |
[編集] パラメータ
| p | - | 格納する例外ポインタ。p がヌルである場合の動作は未定義です。 |
[編集] 戻り値
(なし)
[編集] 例外
std::future_error は、以下の条件で発生します。
- *this が共有状態を持たない場合。エラーコードは no_state に設定されます。
- 共有状態が既に値または例外を格納している場合。エラーコードは promise_already_satisfied に設定されます。
[編集] 例
このコードを実行
#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()); // or throw a custom exception instead // p.set_exception(std::make_exception_ptr(MyException("mine"))); } 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
[編集] 関連項目
| スレッド終了時のみ通知を配信し、結果が例外を示すように設定する (public member function) |