Subj : Re: pthread_cond_signal() semantics To : comp.programming.threads From : Giancarlo Niccolai Date : Sun Jan 09 2005 07:05 pm William Hoggarth wrote: > Thanks for the replies, let's see if I understand correctly: > > 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); >> } > > 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() ). Not exactly, but the net effect is very similar. It also tells the thread that the condition it was waiting for had may have happened in the meanwhile. > > 2) pthread_mutex_unlock(&mutex) merely unlocks the mutex, allowing the > thread to reaquire the lock before the waiting thread can do so. Yes: if the waiting threads cannot get woken up before this thread reacquires the mutex, this may happen, and usually does (unless you are using FIFO mutexes which are often provided as extensions, but that many of us here disapprove). > > 3) the most sensible way to get the behaviour I want is to have another > condition variable which signals when the data has been processed. This is correct under every situation. In fact, even if you had FIFO mutexes that ensure that another waiting thread gets the lock as soon as you release it, swapping your thread out, nothing grants you that the threads that step in is able to perform full data processing before being swapped out and the produced being swapped in again. I.e. the consumer may block on a function, drop its timeslice, do long calculations etc. Having all threads to wait on a FIFO mutex to handle this is, at least, clumsy and inefficient (where not unsafe): producer-consumer relationships is better handled using a pair of conditions: data-ready and data-processed. Waiting on the data-processed condition will make your producer to swap out and to stay out until data is really processed! If your consumers may be able to handle more than one single data at a time, i.e. if you had a queue of data to be processed, the you should sync on queue being full instead: if the queue is full your producer thread will wait until the queue is not full anymore, else it will continue to fill the queue and signal; the consumer(s) will wait while the queue is empty, else will go on processing as fast as they can. This second approach is superior to 1:1 approach (produce-wait for processing) if the producer thread does not depend on the consumer to feed back some results in it in order to produce the very next data. > > Is this right? Yes. Giancarlo. .