问题描述
我有一种情况,可以在wait()之前调用notify().
I have a situation where a notify() 'can' be called before a wait().
当我通过向他发送消息通知"他时,我正在尝试制作一个模拟器来安排其下一个事件.所以我设计了一个wait-> notify->程序链
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();
}
}
这里的问题是:在某些情况下,调用notify()之前要先调用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()怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!