As already indicated, you must either make mStopatomic or protect all its appeals with the help of the mutex. Forget about volatile, this does not apply to your goals.
In addition, when waiting for a state variable, the call waitmay return even if the notification functions were not called (these are the so-called side awakenings). Therefore, you need to protect calls 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);
while(!mStop && q.empty()) mCond.wait(lock);
while(!q.empty())
{
}
if(mStop) return;
}
}
source
share