1 #include <pthread.h> 2 #include <stdio.h> 3 #include <unistd.h> 4 5 //static int x = 0; 6 pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; 7 pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; 8 9 void* doit(void *p) 10 { 11 sleep(*(int *)p); 12 pthread_mutex_lock(&mutex1); 13 //if( x == 0) 14 { 15 printf("pthread_id: %d, wait for command.\n", pthread_self()); 16 pthread_cond_wait(&cond1,&mutex1); 17 } 18 printf("I %d got command,let's go.\n", pthread_self()); 19 pthread_mutex_unlock(&mutex1); 20 return NULL; 21 } 22 23 24 int main() 25 { 26 pthread_t pth_array[5]; 27 28 int i=0; 29 for(;i<5;i++) 30 { 31 pthread_create(&pth_array[i],NULL,doit,&i); 32 } 33 34 35 pthread_mutex_lock(&mutex1); 36 37 pthread_cond_broadcast(&cond1); 38 pthread_mutex_unlock(&mutex1); 39 40 41 i=0; 42 for(;i<5;i++) 43 { 44 pthread_join(pth_array[i],NULL); 45 } 46 47 return 0; 48 }
如果发出信号(pthread_cond_signal, pthread_cond_broadcast)时,没有线程在条件变量的wait
中等待,则这个信号丢失,其他线程走到wait时,投入睡眠状态。
对于本例子中,假设各线程必须要接收该信号(线程还没走到等待,主线程已经发送信号造成丢失),那么
应该使用一个全局变量来标示线程已经处于等待状态,主线程检查该变量,发现所有线程都已经进入等待状态
时,发出信号。