c++ - 如果在 wait() 之前调用 notify() 怎么办?

标签 c++ boost synchronization condition-variable ns-3

我有一种情况,在 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/

相关文章:

c++ - 矩阵乘法 cicle 中的逻辑错误? (C++面向对象)

c++ - e的计算验证

C++ - 如何以平台无关、线程安全的方式将文件的上次修改日期和时间格式化为用户首选的日期/时间区域设置格式

c++ - 使用boost bind访问内部类的成员函数

android - 使用 AsyncTask 时同步线程的问题,Android

android - Volley 库 vs Android SyncAdapter

c++ - 如何构建项目 Visual Studio 可以跨平台运行

c++ - boost::posix_time::time_duration 溢出?

mysql 导入/导出

c++ - 访问属性树中的多值键