如果在 wait() 之前调用 notify() 会怎样?

what if notify() is called before wait()?(如果在 wait() 之前调用 notify() 会怎样?)
本文介绍了如果在 wait() 之前调用 notify() 会怎样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,即可以在 wait() 之前调用 notify().

I have a situation where a notify() 'can' be called before a wait().

当我通过向他发送消息通知"他时,我正在尝试制作一个模拟器来安排它的下一个事件.所以我设计了一个等待->通知->调度链

I am trying to make a simulator to schedule its next event when I 'notify' him by sending him messages. So I have devised a wait->notify->scedule chain

void Broker::pause()
{
    boost::unique_lock<boost::mutex> lock(m_pause_mutex);
    {
        std::cout << "pausing the simulation" << std::endl;
        m_cond_cnn.wait(lock);
        std::cout << "Simulation UNpaused" << std::endl;
        // the following line causes the current function to be called at 
        // a later time, and a notify() can happen before the current function
        // is called again
        Simulator::Schedule(MilliSeconds(xxx), &Broker::pause, this);
    }
}

void Broker::messageReceiveCallback(std::string message) {
    boost::unique_lock<boost::mutex> lock(m_pause_mutex);
    {
        m_cond_cnn.notify_one();
    }
}

这里的问题是:可能存在在调用其 wait() 之前调用 notify() 的情况.

the problem here is that: there can be situations that a notify() is called before its wait() is called.

这种情况有解决办法吗?谢谢

Is there a solution for such situation? thank you

推荐答案

条件变量很难单独使用,因为正如你所注意到的,它们只会唤醒当前等待的线程.还有虚假唤醒的问题(即,条件变量有时可以在没有调用任何相应的 notify 的情况下唤醒线程).为了正常工作,条件变量通常需要另一个变量来保持更可靠的状态.

Condition variables can hardly be used alone, if only because, as you noticed, they only wake the currently waiting threads. There's also the matter of spurious wake-ups (ie. the condition variable can sometimes wake up a thread without any corresponding notify having been called). To work properly, condition variables usually need another variable to maintain a more reliable state.

要解决这两个问题,在您的情况下,您只需要添加一个布尔标志:

To solve both those problems, in your case you just need to add a boolean flag:

boost::unique_lock<boost::mutex> lock(m_pause_mutex);
while (!someFlag)
    m_cond_cnn.wait(lock);
someFlag = false;

//...

boost::unique_lock<boost::mutex> lock(m_pause_mutex);
someFlag = true;
m_cond_cnn.notify_one();

这篇关于如果在 wait() 之前调用 notify() 会怎样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)