在使用packaged_task时,我收集了向量中的所有期货。之后,我用get()推回未来的值。但是,我得到了错误的答案。谁能帮忙?非常感谢你。如何获得未来的价值?
#define BOOST_THREAD_PROVIDES_FUTURE
#include <boost/thread/future.hpp>
#include <vector>
#include <iostream>
using namespace std;
vector<int> subFun(int n) {
vector<int> a{ 2 * n, 3 * n };
return a;
}
int main() {
vector<boost::future<vector<int>>> g;
vector<vector<int>> x(10, vector<int>(2));
int i;
for (i = 0; i < 10; i++) {
boost::packaged_task<vector<int>> task{ boost::bind(&subFun, i) };
g.push_back(task.get_future());
boost::thread t{ std::move(task) };
}
for (auto& m : g) {
x.push_back(m.get());
}
cout << x[3][0] << endl;//should be 6, now is 0
return 0;
}
你为什么不使用'STD :: promise'?顺便说一句,这些现在都在标准库中。而且,标签C++ –
想通了! –