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

编程入门 行业动态 更新时间:2024-10-23 20:28:55
本文介绍了如果在 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() 会怎样?

本文发布于:2023-10-18 10:49:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504013.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:wait   notify

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!