std::condition_variable why does it need a std::mutex

The mutex protects the predicate, that is, the thing that you are waiting for. Since the thing you are waiting for is, necessarily, shared between threads, it must be protected somehow.

In your example above, i == 1 is the predicate. The mutex protects i.

It may be helpful to take a step back and think about why we need condition variables. One thread detects some state that prevents it from making forward progress and needs to wait for some other thread to change that state. This detection of state has to take place under a mutex because the state must be shared (otherwise, how could another thread change that state?).

But the thread can't release the mutex and then wait. What if the state changed after the mutex was released but before the thread managed to wait? So you need an atomic "unlock and wait" operation. That's specifically what condition variables provide.

With no mutex, what would they unlock?

The choice of whether to signal the condition variable before or after releasing the lock is a complex one with advantages on both sides. Generally speaking, you will get better performance if you signal while holding the lock.


A good rule of thumb to remember when working with multiple threads is that, when you ask a question, the result may be a lie. That is, the answer may have changed since it was given to you. The only way to reliably ask a question is to make it effectively single-threaded. Enter mutexes.

A condition variable waits for a trigger so that it can check its condition. To check its condition, it needs to ask a question.

If you do not lock before waiting, then it is possible that you ask the question and get the condition, and you are told that the condition is false. This becomes a lie as the trigger occurs and the condition becomes true. But you don't know this, since there's no mutex making this effectively single-threaded.

Instead, you wait on the condition variable for a trigger that will never fire, because it already did. This deadlocks.