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

履歴 編集

class template
<future>

std::shared_future(C++11)

namespace std {
  template <class R>
  class shared_future;
}

概要

shared_futureは、futureクラスオブジェクトから変換によって生成されるクラスである。futureオブジェクトがpromiseとの共有状態を単一オブジェクトで待機するのに対し、shared_futureオブジェクトは同じ共有状態を複数オブジェクトで待機することを可能にする。

メンバ関数

名前 説明 対応バージョン
(constructor) コンストラクタ C++11
(destructor) デストラクタ C++11
operator= 代入演算子 C++11

値の取得

名前 説明 対応バージョン
get 結果を取得する C++11

状態を確認する関数

名前 説明 対応バージョン
valid 共有状態を持っているかを確認する C++11

待機

名前 説明 対応バージョン
wait 処理が完了するまで待機する C++11
wait_for 相対時間でタイムアウトを指定して、処理が完了するまで待機する C++11
wait_until 絶対時間でタイムアウトを指定して、処理が完了するまで待機する C++11

#include <iostream>
#include <thread>
#include <mutex>
#include <future>

std::mutex print_mtx_;
template <class T>
void print(const T& x)
{
  std::lock_guard<std::mutex> lk(print_mtx_);
  std::cout << x << std::endl;
}

void process(std::shared_future<int> f)
{
  // 各shared_futureオブジェクトから結果値を取り出す
  int result = f.get();

  print(result);
}

int main()
{
  std::promise<int> p;
  std::shared_future<int> f = p.get_future().share();

  std::thread t1(process, f);
  std::thread t2(process, f);

  int value = 3; // 何らかの計算
  p.set_value(value);  // 計算結果を設定する

  t1.join();
  t2.join();
}

出力

3
3

バージョン

言語

  • C++11

処理系

参照