1

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::functions 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 deleted until the threads are joined.

4

1 回答 1

1

std::queue 不是线程安全的。当您说您使用互斥锁从队列中弹出时,我知道您将在队列中执行相同的操作。

此外,您需要照顾 Foo 的生命周期。考虑将 shared_ptr 传递给异步函数。(shared_from_this() 而不是这个)

注意:可以使用 boost::asio 来实现任务调度。这是一篇非常好的文章 http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting-started-with-boostasio/

于 2013-07-15T12:24:01.320 回答