shared_future<R> share();
概要
future
オブジェクトを共有する。
*this
のfuture
オブジェクトと同じ共有状態を持つshared_future
オブジェクトを生成する。
この関数を呼び出したあと、*this
のfuture
オブジェクトは無効となる。
事後条件
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
処理系
- Clang: ??
- GCC: 4.7.0
- ICC: ??
- Visual C++: 2012
参照
futureとshared_future - yohhoyの日記 future::share()は何のためにあるのか - Faith and Brave - C++で遊ぼう