Condition Variable - Wait/Notify Race Condition

蹲街弑〆低调 提交于 2019-12-05 15:17:49
stefaanv

In short: think about condition variables as a method to notify other threads that something has changed, not just as a signal.

In order to do this, the condition variable should accompany a condition (simple example: an integer is incremented) that can be handled by the receiving thread.

Now, to solve your problem, thread 1 can use a condition variable accompanied by a ready boolean to signal the other threads when it is ready to receive the condition variable signal, but you better check first whether the original condition variable can be used as described here.

pseudo code based on question (proper locking of conditionVariable still needed):

// Thread 1
while(1)
{
    lockReady();
    ready = true;
    unlockReady();
    readyCV.notify_one();
    conditionVariable.wait();

    // Do some work
}

// Thread 2
while(1)
{
    lockReady();
    while (! ready) readyCV.wait();
    ready = false;
    unlockReady();
    // Do some work
    conditionVariable.notify_one();
}

// Thread 3
while(1)
{
    lockReady();
    while (! ready) readyCV.wait();
    ready = false;
    unlockReady();
    // Do some work
    conditionVariable.notify_one();
}

see also my previous answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!