Skip to content

Latest commit

 

History

History
93 lines (70 loc) · 2 KB

File metadata and controls

93 lines (70 loc) · 2 KB

share

  • future[meta header]
  • std[meta namespace]
  • future[meta class]
  • function[meta id-type]
  • cpp11[meta cpp]
shared_future<R> share();
  • shared_future[link ../shared_future.md]

概要

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();
}
  • share()[color ff0000]
  • f.get()[link /reference/future/shared_future/get.md]
  • std::promise[link /reference/future/promise.md]
  • p.get_future()[link /reference/future/promise/get_future.md]
  • p.set_value[link /reference/future/promise/set_value.md]

出力

3
3

バージョン

言語

  • C++11

処理系

参照

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