c++ - 使用 boost 条件变量

标签 c++ boost

我正在设计一个异步记录器类,如下所示。但是,不确定我是否以正确的方式使用 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/

相关文章:

c++ - 如何解释 is_assignable 中的 declval<_Dest>() = declval<_Src>()

c++ - 具有必要副作用的静态初始化被优化掉

c++ - 如何从 QMetaObject::invokeMethod 获取返回值

C++ - 在一个函数/文件中初始化变量然后在 main()/另一个文件中使用它的最佳方法是什么?

c++ - 云的PCL注册

c++ - Boost (v1.33.1) 线程中断

c++ - CMake 错误 : Imported targets not available for Boost version 106300

c++ - Boost python,暴露迈耶斯单例

c++ - 我能知道转换中匹配 boost::proto::_ 的类型吗?

c++ - 这个加法类会不会导致内存泄露?