jeudi 7 septembre 2017

why does std::condition_variable::wait need mutex?

TL;DR

Why does std::condition_variable::wait needs a mutex as one of its variables?


Answer 1

You may look a the documentation and quote that:

 wait... Atomically releases lock

But that's not a real reason. That's just validate my question even more: why does it need it in the first place?

Answer 2

predicate is most likely query the state of a shared resource and it must be lock guarded.

OK. fair. Two questions here

  1. Is it always true that predicate query the state of a shared resource? I assume yes. I t doesn't make sense to me to implement it otherwise
  2. What if I do not pass any predicate (it is optional)?

Using predicate - lock makes sense

int i = 0;
void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    cv.wait(lk, []{return i == 1;});
    std::cout << i;
}

Not Using predicate - why can't we lock after the wait?

int i = 0;
void waits()
{
    cv.wait(lk);
    std::unique_lock<std::mutex> lk(cv_m);
    std::cout << i;
}

Notes

I know that there are no harmful implications to this practice. I just don't know how to explain to my self why it was design this way?

Question

If predicate is optional and is not passed to wait, why do we need the lock?

Aucun commentaire:

Enregistrer un commentaire