Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong std::condition_variable example on cppreference?

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?

like image 362
Maikel Avatar asked Dec 06 '25 07:12

Maikel


1 Answers

No, there is no race condition.
Even if the condition variable spuriously wakes up, it must re-acquire the lock. hence, two things happen:

  1. no thread can touch ready while the lock is held, as a lock protects it.
  2. by re-acquiring the lock, the boolean must be synchronized, because the lock enforce memory order acquire, which causes ready to have the latest value.

So there is no way for race condition to happen.

like image 168
David Haim Avatar answered Dec 07 '25 20:12

David Haim