Subj : pthread_cond_broadcast [a little long] To : comp.programming.threads From : fabrizio Date : Tue Jan 25 2005 01:28 pm Hello, I am trying to synchronize a certain number of threads using condvars and encounter some problems. I create a thread that wait for x signals and then broadcast a convar that should start all other threads. I create x threads that signal a condvar, to indicate that they are ready, then wait for the start order. Unfortunately, as the last ready thread signal the ready condvar the thread waiting for the ready event, immediately signal the start order and the last thread has not yet reach the wait instruction. As I imagine it is not very clear, here is a simple program and its output that explicit my problem : ------------- #include #include pthread_cond_t readyvar; pthread_mutex_t readymut; pthread_cond_t startvar; pthread_mutex_t startmut; void* routine0(void* data) { int n=3; while(n > 0) { pthread_mutex_lock(&readymut); printf("%d\twaiting for %d ready\n",(int)pthread_self(),n); pthread_cond_wait(&readyvar,&readymut); n--; printf("%d\tready received\n",(int)pthread_self()); pthread_mutex_unlock(&readymut); } pthread_mutex_lock(&startmut); pthread_cond_broadcast(&startvar); printf("%d\tsignal start\n",(int)pthread_self()); pthread_mutex_unlock(&startmut); return(NULL); } void* routine1(void* data) { pthread_mutex_lock(&readymut); pthread_cond_signal(&readyvar); printf("%d\tsignal ready\n",(int)pthread_self()); pthread_mutex_unlock(&readymut); pthread_mutex_lock(&startmut); printf("%d\twaiting for start order\n",(int)pthread_self()); pthread_cond_wait(&startvar,&startmut); printf("%d\tstart order received\n",(int)pthread_self()); pthread_mutex_unlock(&startmut); return(NULL); } int main() { pthread_t t0,t1,t2,t3; pthread_create(&t0,NULL,routine0,NULL); pthread_create(&t1,NULL,routine1,NULL); pthread_create(&t2,NULL,routine1,NULL); pthread_create(&t3,NULL,routine1,NULL); pthread_join(t0,NULL); } ----------- I modify the output a little so it can be read more easily 16386 waiting for 3 ready 32771 signal ready 16386 ready received 16386 waiting for 2 ready 32771 waiting for start order 49156 signal ready 16386 ready received 16386 waiting for 1 ready 49156 waiting for start order 65541 signal ready 16386 ready received 16386 signal start AT THIS POINT THE START IS SIGNALED BUT THE LAST THREAD IS NOT WAITING FOR 32771 start order received 49156 start order received 65541 waiting for start order ------------------ My question is : how should I design my threads for doing such synchronization ? Any hint on this would be greatly appreciated. Fabrice .