- 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オブジェクトを共有する。
*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();
}- 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
- Clang: ??
- GCC: 4.7.0
- ICC: ??
- Visual C++: 2012
futureとshared_future - yohhoyの日記 future::share()は何のためにあるのか - Faith and Brave - C++で遊ぼう