Re: pthread_cond_signal is mutex lock/unlock needed ?



On Feb 14, 9:47 am, Sergei Organov <o...@xxxxxxxxx> wrote:

Provided you still change the condition itself under protection of
mutex, like this:

pthread_mutex_lock
change condition
pthread_mutex_unlock
pthread_cond_signal

you are safe. Compared to signalling with mutex locked, it could only
lead to additional spurious wakeups.

This is incorrect. You are not necessarily safe. The problem is that
the 'pthread_cond_signal' might signal a thread that blocked after the
'pthread_mutex_unlock' call rather than one that was already blocked.

This can, as Rainer Weikusat explained, lead to *missed* wakeups.
Spurious wakeups are harmless, missed wakeups are not.

Imagine if there are two types threads that might block on the
condition variable. One blocks until something is true and one blocks
until something is false. A thread blocking until the condition is
true will only block if it is false. A thread blocking until the
condition is false will only block if it is true.

If you hold the mutex, and the condition is true, only threads
blocking until it is false can be blocked. Since it's already true, no
threads can be blocking until it's true. So if you signal while
holding the lock and the condition is true, you are guaranteed to
unblock a thread wiating for it to be false. But, if you call
pthread_mutex_unlock before pthread_cond_signal, threads of both types
may be blocked and your pthread_cond_signal may wake a thread of
either type.

It is *usually* safe to move a pthread_cond_signal from inside the
mutex to outside it. But it is not always guaranteed safe. A
'pthread_cond_broadcast', on the other hand, can always be safely
moved.

pthread_mutex_lock
change condition
pthread_mutex_unlock
pthread_cond_signal

This code may wake a thread that blocked after the call to
'pthread_mutex_unlock' and noticed the changed condition.


pthread_mutex_lock
change condition
pthread_cond_signal
pthread_mutex_unlock

This code cannot wake a thread that noticed the changed condition. It
can only unblock a thread that choose to block based on the original
value of the condition.

This is a significant semantic difference.

DS
.