Subj : Re: pthread_cond_signal() semantics To : comp.programming.threads From : Giancarlo Niccolai Date : Sun Jan 09 2005 09:00 am Joseph Seigh wrote: > On Sat, 08 Jan 2005 23:32:01 GMT, William Hoggarth > wrote: > >> 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); >> } >> >> The thread seems to reaquire the mutex lock before the thread I'm >> signalling wakes up. Putting sched_yield() at the end of the loop results >> in the behaviour I'm expecting: the thread waiting on the condition >> variable wakes up, aquiring the mutex. >> >> Does this mean that pthread_cond_signal() allows other threads to lock >> the mutex before the waiting thread wakes up with the lock on the mutex? > > No. >> >> Does pthread_cond_signal() just make the signalled thread runnable, with >> the guarantee of the mutex lock when it runs? > > For some implementations. Others may queue the woken threads onto the > mutex wait queue instead. AFAIK, it is not required; that is the implementations doing it (waking waiting threads immediately) are overdoing their jobs. Many here thinks that waking threads as mutex are unlocked is not good; I am with them. IMHO is incorrect to swap the current thread out as soon as it signals or unolocks and make an older thread immediately runnable: time slice MUST be used as long as possible. Also, this would make absolutely no sense in a SMP environment. If you have two or more processors, then what should happen when signaling? how much fast the other waiting thread(s) may get running in the other processor? Would your signaling thread be swapped? Would it make good to your code and performances? I can see some use for mutex relase-thread wake, that's true, but I can see that with a little more effort any code using waking mutex releases can be at least made more efficient without it. If you want to know that other threads have done their job on incoming data before reading and signaling again, you have to create another condition on job_done and wait for it in the signaling thread; no other (sensible) option. Gian. .