In their example usage of std::condition_variable they have essentially
std::mutex m;
std::condition_variable cv;
bool ready = false;
void worker_thread()
{
// Wait until main() sends data
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});
// more ...
}
int main()
{
std::thread worker(worker_thread);
data = "Example data";
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(m);
ready = true;
}
cv.notify_one();
// more...
}
My problem now is the variable ready which is not declared std::atomic*.
Why doesn't this introduce a race condition if spurious wakeup occurs?
No, there is no race condition.
Even if the condition variable spuriously wakes up, it must re-acquire the lock. hence, two things happen:
ready while the lock is held, as a lock protects it.ready to have the latest value.So there is no way for race condition to happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With