Subj : Re: pthread_cond_signal() semantics To : comp.programming.threads From : Joseph Seigh Date : Sat Jan 08 2005 07:30 pm 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. > > What are the exact semantics of pthread_cond_signal()? What you're seeing isn't caused by pthread_cond_signal. It's caused by the mutex. If it's an adaptive mutex doing a unlock doesn't give the lock to another waiting thread, it just marks the mutex free and wakes up an thread waiting for the mutex. If the thread that unlocked, immediately locks it again, the thread that's waking up doesn't get a chance to lock the mutex. sched_yield lets the other thread get a chance at the lock. The get_input() you're using must not be preempting too often. For other scheduling policies you may get mutexes that guarantee FIFO service order and you'd get the behavior you are expecting. -- Joe Seigh .