使用boost条件变量 [英] Using boost condition variables

查看:208
本文介绍了使用boost条件变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计一个异步记录器类,如下所示。但是,不确定我是否以正确的方式使用boost条件变量。任何人都可以评论这个?这里的processLogEntry方法是一个线程函数,我在这里使用boost。

I am designing an asynchronous logger class as follows. However, not sure if I am using the boost condition variable in the right way. Can anyone comment on this? Here the processLogEntry method is a thread function and I am using boost here.

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 原子或保护所有其对互斥体的访问。

As it has been pointed out, you must either make mStop atomic or guard all its accesses with the mutex. Forget about volatile, it's not relevant to your purposes.

此外,当等待条件变量时,调用 wait 可能返回,即使没有调用通知函数(这些是所谓的虚假唤醒)。因此,对 wait 的调用需要加以保护。

Furthermore, when waiting on a condition variable a call to wait may return even if no notification functions were called (those are so-called spurious wake-ups). As such, calls to wait need to be guarded.

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;
    }
}

这篇关于使用boost条件变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆