• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    class
    <condition_variable>

    std::condition_variable

    namespace std {
      class condition_variable;
    }
    

    概要

    condition_variableは、特定のイベントもしくは条件を満たすまでスレッドの実行を待機するためのクラスである。

    wait()wait_for()wait_until()を使用してスレッドを待機させ、notify_one()notify_all()によって待機しているスレッドを起床させる。

    condition_variablecondition_variable_anyと違い、ロック型としてunique_lock<mutex>のみをサポートしている。これは、処理系にcondition_variableクラスに最も効率の良い実装を許可するためである。(例:POSIXスレッド環境においてはcondition_variablepthread_cond_tの、mutexpthread_mutex_tの単純なラッパクラスとして実装されうる)

    condition_variableの適切な利用については、条件変数の利用方法も参照のこと。

    メンバ関数

    名前 説明 対応バージョン
    (constructor) コンストラクタ C++11
    (destructor) デストラクタ C++11
    operator=(const condition_variable&) = delete; 代入演算子 C++11
    notify_one 待機しているスレッドをひとつ起床させる C++11
    notify_all 待機している全てのスレッドを起床させる C++11
    wait 起床されるまで待機する C++11
    wait_for 相対時間のタイムアウトを指定して、起床されるまで待機する C++11
    wait_until 絶対時間のタイムアウトを指定して、起床されるまで待機する C++11
    native_handle 条件変数のハンドルを取得する C++11

    メンバ型

    名前 説明 対応バージョン
    native_handle_type 実装依存のハンドル型 C++11

    非メンバ関数

    名前 説明 対応バージョン
    notify_all_at_thread_exit 現在のスレッド終了時に、条件変数が待っている全てのスレッドを起床させる C++11

    #include <iostream>
    #include <condition_variable>
    #include <mutex>
    #include <thread>
    
    struct ProcessData {
      std::mutex mtx_;
      std::condition_variable cond_;
    
      bool data_ready_ = false;
    
    public:
      // 処理に必要なデータの準備をする
      void prepare_data_for_processing()
      {
        // ...準備処理...
    
        {
          std::lock_guard<std::mutex> lk(mtx_);
          data_ready_ = true;
        }
    
        // 準備完了したので待機スレッドを起床させる
        cond_.notify_one();
      }
    
      void wait_for_data_to_process()
      {
        std::unique_lock<std::mutex> lk(mtx_);
    
        // データの準備ができるまで待機してから処理する
        cond_.wait(lk, [this] { return data_ready_; });
        process_data();
      }
    
    private:
      void process_data()
      {
        // ...データを処理する...
        std::cout << "process data" << std::endl;
      }
    };
    
    int main()
    {
      ProcessData p;
    
      std::thread t1([&] { p.prepare_data_for_processing(); });
      std::thread t2([&] { p.wait_for_data_to_process(); });
    
      t1.join();
      t2.join();
    }
    

    出力

    process data
    

    バージョン

    言語

    • C++11

    処理系

    参照