扩展代码,
#include <future>
#include <iostream>
#include <thread>
using namespace std;
struct X {
int value;
X(int val) : value(val) {}
friend ostream& operator<<(ostream& os, const X& x) {
os << x.value;
return os;
}
};
void f(promise<X>& px) {
try {
X res(42); // 为了示例,计算一个固定的结果
cout << "Calculating result..." << endl;
this_thread::sleep_for(chrono::seconds(2)); // 模拟计算过程
px.set_value(res);
cout << "Result calculated and set." << endl;
} catch (...) {
px.set_exception(current_exception());
}
}
void g(future<X>& fx) {
try {
cout << "Waiting for result..." << endl;
X v = fx.get(); // if necessary, wait for the value to get computed
cout << "Result received: " << v << endl;
// ... use v ...
} catch (...) {
// ... handle error ...
}
}
int main() {
promise<X> px;
future<X> fx = px.get_future();
thread t1(f, ref(px)); // start a thread for f(px)
thread t2(g, ref(fx)); // start a thread for g(fx)
t1.join(); // wait for the thread to complete
t2.join(); // wait for the thread to complete
return 0;
}