Subj : Re: pthread_cond_signal() semantics To : comp.programming.threads From : Loic Domaigne Date : Sun Jan 09 2005 09:36 pm Hi William Gian answered your questions quite thoroughly already, but I'd like to give you some additional material to your first question. >>I have a thread with similar to the following: >> >> while(1) { >> get_input(); >> >> pthread_mutex_lock(&mutex); >> copy_input_to_buffer(); >> pthread_cond_signal(&cond); >> pthread_mutex_unlock(&mutex); >> } > > > Ok, let's see if I understand this correctly. > > 1) pthread_cond_signal(&cond) simply marks the waiting thread as waiting on > the mutex ( as if it had just called pthread_mutex_lock() and not > pthread_cond_wait() ). No, not necessarily. What you are describing is an optimization that we call "wait morphing". Some implementations are less clever than that: the thread waiting on the condition runs. But as you known, before returning from /pthread_cond_wait()/ it (re)locks the associated mutex. Since the mutex is already locked by the signaller , it just goes sleep again and the thread is put into the list of threads waiting for the mutex. This causes unnecessary context switch. Those can be eliminated by the technic you described. On implementation without the wait morphing optimization, it is usually more efficient to signal while the mutex is unlocked. Thus something like: while(1) { get_input(); pthread_mutex_lock(&mutex); copy_input_to_buffer(); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); } Exactly for the same reason as above. As soon as the thread is signaled, it runs. But that times the mutex is unlocked... Of course, if a third thread is also waiting on the mutex, it might run before the waiter... Hope this Help! Cheers, Loic. .