Mutex protecting std::condition_variable

后端 未结 2 541
暖寄归人
暖寄归人 2021-01-14 08:52

Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread. Any threa

2条回答
  •  爱一瞬间的悲伤
    2021-01-14 09:17

    The mutex-protected flag must be set, and the condition variable get signalled, while the mutex is still being held:

    {
        std::lock_guard lock(m);
        proceed = true;
        cv.notify_one();
    }
    

    Furthermore, in this case the proceed flag does not need to be an atomic entity. A simple

    bool proceed;
    

    will be sufficient. With access to proceed happening only while holding the associated mutex, making proceed atomic accomplishes absolutely nothing.

    atomic entities are for handling exotic concurrency situations that do not involve any mutexes in the first place.

提交回复
热议问题