我有一种情况,在 wait() 之前“可以”调用 notify()。
我正在尝试制作一个模拟器,以便在我通过向他发送消息来“通知”他时安排它的下一个事件。所以我设计了一个 wait->notify->scedule 链
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() 的情况。
这种情况有解决办法吗? 谢谢
最佳答案
条件变量几乎不能单独使用,如果仅仅是因为,如您所见,它们只会唤醒当前等待的线程。还有虚假唤醒的问题(即条件变量有时可以在没有调用任何相应的 notify
的情况下唤醒线程)。为了正常工作,条件变量通常需要另一个变量来维持更可靠的状态。
要解决这两个问题,在您的情况下您只需要添加一个 bool 标志:
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();
关于c++ - 如果在 wait() 之前调用 notify() 怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17562908/