Subj : Re: Condition variables & mutexes To : comp.programming.threads From : Torsten Robitzki Date : Tue Jan 25 2005 07:16 pm Ian Pilcher wrote: > I'm making my first attempt to use a condition variable, and I'm > struggling with how exactly I'm supposed to use the associated mutex. > > I finally got a simple example program to work (not hang): > > #include > #include > > #include > > static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; > static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; > > static void *thread(void *arg) > { > puts("thread: started"); > pthread_mutex_lock(&mutex); > puts("thread: mutex locked"); > pthread_cond_signal(&cond); > puts("thread: condition signalled"); > pthread_mutex_unlock(&mutex); > puts("thread: mutex unlocked"); > > return NULL; > } > > int main(void) > { > pthread_t tid; > > puts("main: started"); > pthread_mutex_lock(&mutex); > puts("main: mutex locked"); > pthread_create(&tid, NULL, thread, NULL); > puts("main: thread created"); > pthread_cond_wait(&cond, &mutex); > puts("main: condition signalled"); > pthread_join(tid, NULL); > puts("main: thread joined"); > > return 0; > } > > Is this basically correct, or is my use of the mutex "overkill"? As you don't use the mutex to prevent the threads from accessing shared data, it's probably "overkill" ;-). With a condition variable you can wait for a user defined predicate to become true. And you should wait for the predicate in a loop testing the predicate to become true. If you change the shared data you should do it with the mutex at hand and signal the condition variable if the predicate became true due to your change. This would result in something like this: bool predicate = false; static void *thread(void *arg) { pthread_mutex_lock(&mutex); predicate = true; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); return NULL; } int main(void) { pthread_t tid; pthread_create(&tid, NULL, thread, NULL); pthread_mutex_lock(&mutex); while ( !predicate ) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); pthread_join(tid, NULL); return 0; } but it's hard to see, why you don't just join the thread. regards Torsten .