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

履歴 編集

function
<future>

std::future::share(C++11)

shared_future<R> share();

概要

futureオブジェクトを共有する。

*thisfutureオブジェクトと同じ共有状態を持つshared_futureオブジェクトを生成する。

この関数を呼び出したあと、*thisfutureオブジェクトは無効となる。

事後条件

valid() == false

戻り値

shared_future<R>(std::move(*this))

#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

処理系

参照

futureとshared_future - yohhoyの日記 future::share()は何のためにあるのか - Faith and Brave - C++で遊ぼう