Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Q: Read the manual (or any resources) about the implementation of PThread condit

ID: 3844992 • Letter: Q

Question

Q: Read the manual (or any resources) about the implementation of PThread condition variables and give answer to following questions:
1. Why the condition variable requires a mutex?
2. What happens if a thread is woken up (from wait) but cannot acquire the lock?
3. When signal happens for a condition, and if more than one thread are waiting for that condition:
a. How many threads will be woken up?
b. Could you ensure an order among the threads for waking up? If yes, how?
c. How can you make all the threads to wake up?

Explanation / Answer

1).

The mutex is used to protect the condition variable itself. That's why you need it locked before you do a wait.

The wait will "atomically" unlock the mutex, allowing others access to the condition variable (for signalling). Then when the condition variable is signalled 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.

You typically see the following operation with condition variables, illustrating how they work. The following example is a worker thread which is given work via a signal to a condition variable.

2).I just want to add here my two cents with regards to a less-obvious implied behavior when working with pthread condition variable + a mutex. Considere the sequence below:

3) A thread can call function cond_wait() to block itself until the event represented by that condition variable occurs.