#include<stdio.h> #include<pthread.h> #include<unistd.h> pthread_mutex_t mutex; pthread_cond_t cond; void *child1 (void *arg) { pthread_cleanup_push((void *)pthread_mutex_unlock,(void *)&mutex);//注释1 while(1) {printf("thread1 get running \n"); printf("thread1 pthread_mutex_lock returns %d\n",pthread_mutex_lock(&mutex)); pthread_cond_wait(&cond,&mutex); printf("thread1 condition applied\n"); pthread_mutex_unlock(&mutex); sleep(5); } pthread_cleanup_pop(0);//注释2 } void *child2 (void *arg) { while(1) {sleep(3);//注释3 printf("thread2 get running \n"); printf("thread2 pthread_mutex_lock returns %d\n",pthread_mutex_lock(&mutex)); pthread_cond_wait(&cond,&mutex); printf("thread2 condition applied\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main() {pthread_t tid1,tid2; printf("hello condition variable test\n"); pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond,NULL); pthread_create(&tid1,NULL,child1,NULL); pthread_create(&tid2,NULL,child2,NULL); do{ sleep(2);//注释4 pthread_cancel(tid1);//注释5 sleep(2);//注释6 pthread_cond_signal(&cond); }while(1); sleep(100); pthread_exit(0); return 0; }
若是不执行注释5的pthread_cancle()动做,那么即便没有sleep()延时操做,child1和child都能正常工做。注释3和
注释4的延迟使child1有时间完成取消动做,使child2能在child1退出后执行请求锁操做。若是没有注释1和注释2的
回调函数的定义,则系统将挂起在child2请求锁的地方;若是不作注释3也不作注释4的延时,则child2能在child1
完成取消动做以前获得控制,从而顺利执行申请锁的操做,但却可能在child_cond_wait()中挂起,由于其中也有申请
mutex的操做。child1函数给出的是标准的条件变量的使用方式:回调函数保护,等待条件前锁定,child_cond_wait()
返回后解锁。条件变量机制不是异步信号安全的,也就是说,在信号处理函数中调用pthread_cond_signal()或
pthread_cond_broadcast()极可能引发死锁!!安全
程序运行结果为:app
能够看出最后一直在执行线程2,由于线程1被取消了! 这就是要加-lpthread的缘由!!