When I see a question about the multi-threaded condition variable on the StackOverflow, the question asks: when will the condition variable be used and the mutex is not enough? There is a person called Slowjelj to do a very good answer, I see this buddy other topics of some answers, feel good level. Here to paste his answer for easy viewing later, the original post here: When is a conditional variable needed, isn ' t a mutex enough?
Even though you can use them in the the-the-describe, mutexes weren ' t designed for use as a notification/synchronization m Echanism. They is meant to provide mutually exclusive access to a shared resource. Using mutexes to signal a condition are awkward and I suppose would look something like this (where Thread1 was signaled by THREAD2):
Thread1:
while(1) { lock(mutex); // Blocks waiting for notification from Thread2 ... // do work after notification is received unlock(mutex); // Tells Thread2 we are done}
Thread2:
while(1) { ... // do the work that precedes notification unlock(mutex); // unblocks Thread1 lock(mutex); // lock the mutex so Thread1 will block again}
There is several problems with this:
- thread2 cannot continue to "does the work that precedes notification" until Thread1 h As finished with ' work after notification '. With this design, Thread2 are not even necessary, that's, why isn't move "work that precedes" and "work after notification" Into the same thread since only one can run at a given time!
- if Thread2 is not able to preempt Thread1, Thread1 would immediately re-lock the mutex whe n It repeats the while (1) loop and Thread1 would go about doing the ' work after notification ' even though there was no Noti Fication. This means your must somehow guarantee that THREAD2 would lock the mutex before Thread1 does. How does that? Maybe force a schedule event by sleeping, or by some other os-specific means but even this is not guaranteed to work depend ing on timing, your OS, and the scheduling algorithm.
These problems aren ' t minor, in fact, they is both major design flaws and latent bugs. The origin of both of these problems is the requirement, a mutex is locked and unlocked within the same thread. So how does you avoid the above problems? Use condition variables!
BTW, if your synchronization needs is really simple, you could use a plain old semaphore which avoids the additional comp Lexity of condition variables.
Here's a good article, Efficient development experience of multithreaded programming for Linux , but also interspersed with some of the experience of multithreaded programming under Windows, worth reading.
Conditional variables for Linux multithreaded programming