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

2023-09-08 09:43:27 作者:甜度爆表

我有一种情况,即可以在 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();
 
精彩推荐