1 int pthread_cond_init(pthread_cond_t *cond,pthread_condattr_t *cond_attr); 2 int pthread_cond_wait(pthread_cond_t *cond,pthread_mutex_t *mutex); 3 int pthread_cond_timewait(pthread_cond_t *cond,pthread_mutex *mutex,const timespec *abstime); 4 int pthread_cond_destroy(pthread_cond_t *cond); 5 int pthread_cond_signal(pthread_cond_t *cond); 6 int pthread_cond_broadcast(pthread_cond_t *cond); //解除所有线程的阻塞
简单实例分析:
子线程:
11 while (1) { 12 13 printf("thread1 is running\n"); 14 15 pthread_mutex_lock(&mutex); 16 printf("pthread1"); 17 // fflush(NULL); 18 pthread_cond_wait(&cond, &mutex); 19 20 printf("thread1 applied the condition\n"); 21 for(i=0;i<1000;i++) 22 { 23 printf("i:%d\n",i); 24 } 25 26 pthread_mutex_unlock(&mutex); 27 28 sleep(4); 29 30 }
70 pthread_create(&thid1, NULL, (void *) thread1, NULL); 71 72 // pthread_create(&thid2, NULL, (void *) thread2, NULL); 73 74 do { 75 76 pthread_cond_signal(&cond); 77 78 } while (1);流程:
1)pthread_mutex_lock上锁
2)pthread_cond_wait释放锁,并阻塞等待条件为真(signal信号)
3)主线程发送signal信号,pthread_cond_wait返回并加锁
4)在互斥区进行1000次加法运算并打印,完成后解锁
说明:
1)wait之后锁会被释放,这时候其它线程就可以获得锁
2)如子线程中代码,lock之后printf若不fflush不会有输出,因为其还来不及输出到终端线程就阻塞
二 pthread_atfork
②parent和child函数的调用顺序与注册顺序相同。