名前空間
変種
操作

std::promise<R>::set_exception

From cppreference.com
< cpp‎ | thread‎ | promise
 
 
並行性サポートライブラリ
スレッド
(C++11)
(C++20)
this_thread 名前空間
(C++11)
(C++11)
(C++11)
協調的なキャンセル
排他制御
(C++11)
汎用ロック管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
条件変数
(C++11)
セマフォ
ラッチとバリア
(C++20)
(C++20)
future
(C++11)
(C++11)
(C++11)
(C++11)
安全なメモリ解放 (Safe Reclamation)
(C++26)
ハザードポインタ
アトミック型
(C++11)
(C++20)
アトミック型の初期化
(C++11)(C++20で非推奨)
(C++11)(C++20で非推奨)
メモリオーダー
(C++11)(C++26で非推奨)
アトミック操作のためのフリー関数
アトミックフラグのためのフリー関数
 
 
void set_exception( std::exception_ptr p );
(C++11以降)

アトミックに、共有状態に例外ポインタ p を格納し、状態を準備完了にします。

この操作は、set_valueset_exceptionset_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) [編集]
English 日本語 中文(简体) 中文(繁體)