I’m currently using the boost threadpool with the number of threads equal to the number of cores. I have scheduled, say 10 tasks using the pool’s schedule function. For example,
suppose I have the function
void my_fun(std::vector<double>* my_vec){
// Do something here
}
The argument ‘my_vec’ here is just used to do some temporary calculations. The main reason I passing it the function is that I would like to reuse this vector when I call the function again.
Currently, I have the following
// Create a vector of 10 vectors called my_vecs
// Create threadpool
boost::threadpool::pool tp(num_threads);
// Schedule tasks
for (int m = 0; m < 10; m++){
tp.schedule(boost::bind(my_fun, my_vecs.at(m)));
}
This is my problem: I would like to replace the vector of 10 vectors with only 2 vectors. If I want to schedule 10 tasks and I have 2 cores, a maximum of 2 threads (tasks) will be running at any time. So I only want to use two vectors (one assigned to each thread) and use it to carry out my 10 tasks. How can I do this?
I hope this is clear. Thank You!
Probably
boost::thread_specific_ptris what you need. Below is how you may use it in your function:It will reuse vector instances between tasks scheduled to the same thread. There might be more than 2 instances if there are more threads in the pool, but due to preemption mentioned in other answers you really need an instance per running thread, not per core.
You should not need to delete vector instances stored in
thread_specific_ptr; those will be automatically destroyed when corresponding threads finish.