【发布时间】:2017-10-19 01:12:49
【问题描述】:
在使用 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++ -
想通了!
标签: c++ multithreading boost