I have a simple thread pool implementation using boost::function
, and boost::bind
to reduce the member function signature to void func(void)
. This then uses a queue of boost::function
and int
pairs, pops the top of the queue, and executes the function (all wrapped in a mutex block).
threadPool->addJob(boost::bind(&Foo::bar, this, arg1, arg2));
...
typedef boost::function<void(void)> func;
std::queue<std::pair<func, int> > funcQ;
void ThreadPool::addJob(func f){
funcQ.push(std::make_pair(f, j));
}
if (!funcQ.empty()){
func localFunc = (funcQ.front()).first;
...
funcQ.pop();
...
localFunc();
}
However, after a few iterations, this was causing a segfault when I invoked the ()
operator on the function, so I tossed in an assert statement to make sure that the function was callable:
...
assert(funcQ.front().first);
func localFunc = (funcQ.front()).first;
...
Lo and behold, after a few iterations the assert trips, indicating that my boost::function
was not callable.
I first thought that perhaps the function data (from the Foo
class) had been destroyed before the function was called, however as I understand it, boost::function
creates a copy of the data to form the closure anyhow. Unfortunately I don't know enough about what causes boost::function
s to be invalid to progress any further on the problem. Am I binding the member function incorrectly, or does the problem lie somewhere between there and trying to call it?
Edit: I should have mentioned: Foo
is allocated on the heap, and isn't delete
d until the threads are joined.