I’m looking at code in the textbook: Programming With POSIX Threads by David R. Butenhof, and I came across a place that has me a little confused.
In the code, a cleanup handler is registered for a thread. The cleanup handler unlocks a mutex that is used by the condition within that thread.
With threads in genereal, when a pthread_cond_wait is called (with the related mutex locked as it should be), the mutex is unlocked while the thread waits – it is then reacquired when the condition wait is over, before it returns (i.e. a signal or broadcast happened).
Since, while waiting, a condition_wait doesn’t have the mutex locked, I would have thought that if a thread was cancelled while waiting, it would still not have that mutex locked – so why would the cleanup handler need to free it?
In fact, I thought unlocking a mutex that was already unlocked was actually an error, making this worse. Can someone tell me where you think I’m confused?
You are correct about unlocking a mutex that is already unlocked being a Bad Thing™.
However, while
pthread_cond_wait()is a cancellation point, the interface guarantees that the mutex is reacquired before the cancellation handler runs. If it did not make this guarantee it would be very difficult to know whether or not the mutex was held.See: The specification for details.