我正在设计一个异步记录器类,如下所示。但是,不确定我是否以正确的方式使用 boost 条件变量。有人可以对此发表评论吗?这里的 processLogEntry 方法是一个线程函数,我在这里使用了 boost。
void LogWriter::stopThread()
{
mStop = true;
mCond.notify_one();
mThread->join();
}
void LogWriter::processLogEntry()
{
while(!mStop)
{
boost::mutex::scoped_lock lock(mMutex);
mCond.wait(lock);
while(!q.empty())
{
// process begins
}
}
}
void LogWriter::addLogEntry()
{
boost::mutex::scoped_lock lock(mMutex);
// add it in the queue
mCond.notify_one();
}
最佳答案
正如已经指出的那样,您必须使 mStop
成为原子的,或者使用互斥锁保护所有它的访问。忘记 volatile
,它与您的目的无关。
此外,当等待条件变量时,即使没有调用通知函数,对 wait
的调用也可能返回(这些就是所谓的虚假唤醒)。因此,需要保护对 wait
的调用。
void LogWriter::stopThread()
{
{
boost::mutex::scoped_lock lock(mMutex);
mStop = true;
mCond.notify_one();
}
mThread->join();
}
void LogWriter::processLogEntry()
{
for(;;) {
boost::mutex::scoped_lock lock(mMutex);
// We wait as long as we're not told to stop and
// we don't have items to process
while(!mStop && q.empty()) mCond.wait(lock);
// Invariant: if we get here then
// mStop || !q.empty() holds
while(!q.empty())
{
// process begins
}
if(mStop) return;
}
}
关于c++ - 使用 boost 条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12345844/