In: Computer Science
Explain why it is necessary to use a mutex lock in conjunction with a condition variable.
Necessary to use a mutex lock in conjunction with a condition variable:-
1. The mutex is used to protect the condition variable itself. That's why you need it locked before do it.
2. Condition variables can be used to atomically block threads until a particular condition is true.
3. The wait will "atomically" unlock the mutex, allowing others access to the condition variable. Then when the condition variable is signaled or broadcast to, one or more of the threads on the waiting list will be woken up and the mutex will be magically locked again for that thread.
4. Condition variables are always used in conjunction with mutex locks:
a. With a condition variable, a thread can atomically block until a condition is satisfied.
b. The condition is tested under the protection of a mutual exclusion lock (mutex).
i. When the condition is false, a thread usually blocks on a condition variable and atomically releases the mutex waiting for the condition to change.
ii. When another thread changes the condition, it can signal the associated condition variable to cause one or more waiting threads to wake up, acquire the mutex again, and revaluate the condition.
5. Condition variables can be used to synchronize threads among processes when they are allocated in memory that can be written to and is shared by the cooperating processes.
6. The condition variable attributes must be initialized and set (or set to NULL) before an actual condition variable may be initialize and then used.