I have some work that needs to be done in separate threads, the work is done on a std::vector<T> of objects.
I need to do the work and then in the main thread, wait on all the threads with a join().
I have done this the following way, but I think this isn’t a good idea, as I have only one pointer, and it points to something else each iteration of the loop.
struct properties
{
explicit properties(someobj obj) : obj_(obj) {}
void operator()() { /*do something*/ }
someobj obj_;
};
boost::shared_ptr<boost::thread> t;
for (size_t tst = 0; tst <= myvector.size() - 1; ++tst)
{
properties props(myvector[tst]);
t = boost::shared_ptr<boost::thread>(new boost::thread(props));
}
//get main thread to wait till all t's are done, however is this a smart way to wait on multiple t's?? Which t is it going to wait on?
t->join();
Can anybody suggest a better way of doing this? Should I make a vector<boost::shared_ptr<boost::thread>> and loop through them and through my object vector?
You need to use a thread pool. Boost might provide one, though I don’t think it does. PPL and TBB provide them in their
parallel_for_eachfunctions.Loosely, the
thread_groupclass provided by Boost should be what you need.Fundamentally,
boost::threadis a wrapper on the OS thread, it’s not really a solid threading base. PPL and TBB provide parallel algorithms and data structures, which is much better to go.