0

I'm quite confused with the need of a std::unique_lock when wait a std::conditional_variable. So I look into the library code in VS 2013 and get more confused. This is how std::conditional_variable::wait() implemented:

void wait(unique_lock<mutex>& _Lck)
    {   // wait for signal
    _Cnd_waitX(&_Cnd, &_Lck.mutex()->_Mtx);
    }

Is this some kind of joke? Wrap a mutex in a unique_lock and do nothing but get it back latter? Why not just use mutex in the parameter list?

  • 1
    You might want to read this question http://stackoverflow.com/q/2763714 it's pthread specific, but applies to this case as well. – Hasturkun Oct 24 '13 at 15:22

2 Answers2

3

The idea is that when you call wait, you want to be signaled when the value of some variable changes (hence condition_variable). Now, since you are accessing the variable in question from multiple threads (otherwise you wouldn't need synchronization), it will probably be protected by a mutex. So, while you wait for the variable to change, you have to relinquish the mutex, and when you get the signal, you have to reaquire it. This is what this function does for you.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • 1
    what if that variable is of atomic type? –  Oct 24 '13 at 15:15
  • That is a good question. I don't have an answer to that. – Björn Pollex Oct 24 '13 at 15:18
  • 2
    @Mike: You'll still need the mutex. Modifying the state may be atomic; but the actions you need to be atomic are "modify and notify" and "test and wait". Otherwise, you might wait forever if notification happens after you've checked the value but before you start waiting. – Mike Seymour Oct 24 '13 at 16:12
0

Problem is that when you wake up after got signaled you need to have mutex locked already. If you would try to lock mutex after you wake up by signal you would get race condition. On another side wait on condition variable cannot lock that mutex by itself, as it would not be able to properly return lock to you and usually you should lock mutex before you get into wait anyway.

Slava
  • 43,454
  • 1
  • 47
  • 90