C++ 队列(多个生产者和消费者)的并发访问问题-C++;,促进

C++ 队列(多个生产者和消费者)的并发访问问题-C++;,促进,c++,boost,concurrency,producer-consumer,C++,Boost,Concurrency,Producer Consumer,我正在编写一个具有事件队列的应用程序。我的意图是以这样一种方式创建它:多个线程可以写入,一个线程可以从队列中读取,并将弹出元素的处理交给另一个线程,以便后续的弹出不会再次被阻止。我使用锁和条件变量从队列中推送和弹出项目: void Publisher::popEvent(boost::shared_ptr<Event>& event) { boost::mutex::scoped_lock lock(queueMutex); while(eventQueue

我正在编写一个具有事件队列的应用程序。我的意图是以这样一种方式创建它:多个线程可以写入,一个线程可以从队列中读取,并将弹出元素的处理交给另一个线程,以便后续的弹出不会再次被阻止。我使用锁和条件变量从队列中推送和弹出项目:

void Publisher::popEvent(boost::shared_ptr<Event>& event) {

    boost::mutex::scoped_lock lock(queueMutex);
    while(eventQueue.empty())
    {
        queueConditionVariable.wait(lock);
    }
    event = eventQueue.front();
    eventQueue.pop();
    lock.unlock(); 
}

void Publisher::pushEvent(boost::shared_ptr<Event> event) {

    boost::mutex::scoped_lock lock(queueMutex);
    eventQueue.push(event);
    lock.unlock();
    queueConditionVariable.notify_one();

}
void Publisher::popEvent(boost::shared_ptr&event){
boost::mutex::作用域锁定(queueMutex);
while(eventQueue.empty())
{
queueConditionVariable.wait(锁);
}
event=eventQueue.front();
eventQueue.pop();
lock.unlock();
}
void Publisher::pushEvent(boost::共享\u ptr事件){
boost::mutex::作用域锁定(queueMutex);
eventQueue.push(事件);
lock.unlock();
queueConditionVariable.notify_one();
}
在Publisher类的构造函数中(只创建了一个实例),我启动一个线程,该线程将在循环中迭代,直到捕获notify_one(),然后启动另一个线程来处理从队列中弹出的事件:

在构造函数中:

publishthreadGroup = boost::shared_ptr<boost::thread_group> (new boost::thread_group());
publishthreadGroup->create_thread(boost::bind(queueProcessor, this));
publishthreadGroup=boost::shared_ptr(新的boost::thread_group());
publishthreadGroup->创建_线程(boost::bind(queueProcessor,this));
队列处理器方法:

void queueProcessor(Publisher* agent) {

while(true) {
    boost::shared_ptr<Event> event;
    agent->getEvent(event);
    agent->publishthreadGroup->create_thread(boost::bind(dispatcher, agent, event));

    }
}
void队列处理器(发布者*代理){
while(true){
boost::共享的ptr事件;
agent->getEvent(事件);
代理->发布线程组->创建线程(boost::bind(dispatcher、agent、event));
}
}
在dispatcher方法中,完成相关处理,并通过thrift将处理后的信息发布到服务器。在另一个在程序存在之前调用的方法中,即在主线程中,我调用join_all(),以便主线程等待线程完成

在这个实现中,在为dispatcher创建线程之后,在上面的while循环中,我遇到了死锁/挂起。运行的代码似乎被卡住了。实施过程中的问题是什么?有没有一种更干净、更好的方法来做我想做的事情?(多个生产者和一个消费者线程在队列中迭代,并将元素的处理交给不同的线程)


谢谢大家!

似乎
queueProcessor
函数将永远运行,运行它的线程将永远不会退出。由该函数创建的任何线程都将执行其工作并退出,但此线程(在
publishthreadGroup
中创建的第一个线程)有一个
while(true)
循环,无法停止。因此,对
join\u all()
的调用将永远等待。您可以创建一些其他标志变量来触发该函数退出循环并返回吗?那就应该成功了

您可以发布完整的示例吗?我假设在您的
queueProcessor
方法中,您打算调用
agent->popEvent(event)
,而不是
agent->getEvent(event)