我有点卡住了这个问题,所以这是我的呼救声。死锁与提升:: condition_variable
我有一个管理器将某些事件推送到队列中,这是在另一个线程中进行的。 我不希望此线程在队列中的事件“忙于等待”,因为它可能一直为空(以及它可能始终为满)。 另外,我需要m_bShutdownFlag
来在需要时停止线程。 所以我想尝试一下condition_variable
这种情况:如果有东西被推到队列中,那么线程就开始工作。
简化代码:
class SomeManager {
public:
SomeManager::SomeManager()
: m_bShutdownFlag(false) {}
void SomeManager::Initialize() {
boost::recursive_mutex::scoped_lock lock(m_mtxThread);
boost::thread thread(&SomeManager::ThreadProc, this);
m_thread.swap(thread);
}
void SomeManager::Shutdown() {
boost::recursive_mutex::scoped_lock lock(m_mtxThread);
if (m_thread.get_id() != boost::thread::id()) {
boost::lock_guard<boost::mutex> lockEvents(m_mtxEvents);
m_bShutdownFlag = true;
m_condEvents.notify_one();
m_queue.clear();
}
}
void SomeManager::QueueEvent(const SomeEvent& event) {
boost::lock_guard<boost::mutex> lockEvents(m_mtxEvents);
m_queue.push_back(event);
m_condEvents.notify_one();
}
private:
void SomeManager::ThreadProc(SomeManager* pMgr) {
while (true) {
boost::unique_lock<boost::mutex> lockEvents(pMgr->m_mtxEvents);
while (!(pMgr->m_bShutdownFlag || pMgr->m_queue.empty()))
pMgr->m_condEvents.wait(lockEvents);
if (pMgr->m_bShutdownFlag)
break;
else
/* Thread-safe processing of all the events in m_queue */
}
}
boost::thread m_thread;
boost::recursive_mutex m_mtxThread;
bool m_bShutdownFlag;
boost::mutex m_mtxEvents;
boost::condition_variable m_condEvents;
SomeThreadSafeQueue m_queue;
}
但是,当我有两个(或更多)几乎同时呼叫测试,以QueueEvent
,它在该行boost::lock_guard<boost::mutex> lockEvents(m_mtxEvents);
被锁定,直到永远。
似乎第一个电话永远不会释放lockEvents
,所以其余的只是等待其释放。
请帮我找出我做错了什么,以及如何解决这个问题。
谢谢,我已修复#1和#2。我的问题的原因是在队列元素的处理中。由于处理过程中的'while'周期不好,有几个元素永远持续处理。 – Ganya