How do I use a vector of boost thread futures?
How can I use a vector of thread futures to get the return values from a group of threads? Should this work? If not, how do I adapt it?
int calculate_the_answer_to_life_the_universe_and_everything()
{
return 42;
}
vector<开发者_运维知识库;packaged_task<int> > tasks;
vector<unique_future<int> > futures;
for (int i=0; i < 4; ++i)
{
tasks.push_back(packaged_task<int>(calculate_the_answer_to_life_the_universe_and_everything));
futures.push_back(tasks.back().get_future());
thread task(tasks.back());
}
boost::wait_for_all(futures.begin(), futures.end());
Well this code doesn't compile because packaged tasks are not copyable.
Based on the problem statement, all you need is a vector of futures, though, why even try to store packaged_tasks?
#include <boost/thread.hpp>
#include <iostream>
#include <vector>
int the_answer()
{
return 42;
}
int main()
{
std::vector<boost::unique_future<int> > futures;
for (int i=0; i < 4; ++i)
{
boost::packaged_task<int> pt(the_answer);
futures.push_back(pt.get_future());
boost::thread task(std::move(pt));
}
boost::wait_for_all(futures.begin(), futures.end());
for(size_t n=0; n<futures.size(); ++n)
std::cout << futures[n].get() << ' ';
std::cout << '\n';
}
精彩评论