スレッドの返値
以下のコードは、各スレッドから計算結果を取得、表示します。結果を取得するための future は、promise に関連づけられているので、それを使います。
// promise.cpp
#include <functional>
#include <future>
#include <iostream>
#include <thread>
using namespace std;
int int1() {
return 1;
}
int int2() {
return 2;
}
void to_promise(int(*calc)(), promise<int> & p) {
p.set_value(calc());
}
int main(int, char *[]) {
promise<int> p1, p2;
future<int> f1 = p1.get_future(), f2 = p2.get_future();
thread t1(&to_promise, int1, ref(p1)), t2(&to_promise, int2, ref(p2));
int result = f1.get() + f2.get();
t1.join();
t2.join();
cout << "result = " << result << endl;
return 0;
}
promise はコピー禁止なので ref を使う必要があります。
© 2012 Gallonworks

