So I have something like
typedef boost::function<void(DataType)> Function;
typedef std::vector<Function> FunctionSequence;
typedef typename FunctionSequence::iterator FunctionIterator;
DataType* dataElement;
FunctionSequence funcs;
//...
for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it){
DataType dataCopy;
dataCopy = *dataElement;
(*it)(dataCopy);
How using boost.thread make each vector function run in separate new thread or if its better have a vector of threads so not to create therad each time?
If what you're trying to do is launch a new thread for each function, and pass in a copy of your DataType object, you'll want to use Boost Threads and Boost Bind:
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
boost::thread_group tg;
for (FunctionIterator it(funcs.begin()); it != funcs.end(); ++it)
{
tg.create_thread(boost::bind(*it, *dataElement));
}
tg.join_all();
First, you create a boost::thread_group
which will serve as a container for all of the threads that you launch. Then create_thread
will launch a new thread and invoke the function passed to it. In this case, we want to invoke more than a simple function, so we need to use boost::bind
to create a void()
function that the thread can run. The call to boost::bind
first specifies the function to call, and then any parameters to pass to the function. It will already copy the argument, so there's no need to create another copy beforehand.
After you launch all the threads, you can call tg.join_all()
to wait for all the threads to finish before continuing. Calling join_all()
is very important and ensures that the threads don't run rogue in the background.
Obviously, if you have a lot of functions to call and don't want that many threads created, you'll have to track the number of outstanding threads and only create new ones once existing threads exit. This will require some extra book keeping inside the function that is called (and may involve wrapping the function). It's probably not needed in your case.