1#include <pthread.h>2#include <stdio.h>3#include <unistd.h>4 5 //static int x = 0;6pthread_mutex_t mutex1 =Pthread_mutex_initializer;7pthread_cond_t Cond1 =Pthread_cond_initializer;8 9 void* DOIT (void*p)Ten { OneSleep (* (int*) (p); APthread_mutex_lock (&mutex1); - //if (x = = 0) - { theprintf"pthread_id:%d, wait for command.\n", Pthread_self ()); -Pthread_cond_wait (&cond1,&mutex1); - } -printf"I%d got Command,let ' s go.\n", Pthread_self ()); +Pthread_mutex_unlock (&mutex1); - returnNULL; + } A at - intMain () - { -pthread_t pth_array[5]; - - intI=0; in for(;i<5; i++) - { toPthread_create (&pth_array[i],NULL,doit,&i); + } - the *Pthread_mutex_lock (&mutex1); $ Panax NotoginsengPthread_cond_broadcast (&cond1); -Pthread_mutex_unlock (&mutex1); the + AI=0; the for(;i<5; i++) + { - Pthread_join (pth_array[i],null); $ } $ - return 0; -}
If a signal (pthread_cond_signal, pthread_cond_broadcast) is signaled, there is no thread in the wait for the condition variable
Wait, the signal is lost and the other threads go to sleep when they come to wait.
Here you can add an X, the value of the broadcast in the number of threads, the thread to determine if its value is 0, then wait, otherwise, minus one, indicating that it received. Therefore, I think the condition variable should be used with a global variable.
Multi-threaded broadcast