#include<stdio.h> #include<pthread.h> #include<unistd.h> pthread_mutex_t mutex; pthread_cond_t cond; void *child (void *arg) {pthread_cleanup_push(pthread_mutex_unlock,&mutex); 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); } void *child (void *arg) { while(1) {sleep(3);//注释1 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() {int 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,child1,NULL); do{ sleep(2);//此语句(注释2)和注释1的作用是使tid1有时间完成取消动作! pthread_cancle(tid1);//没有此语句程序照样可以执行的。 sleep(2); pthread_cond_signal(&cond); }while(1); sleep(100); pthread_exit(0); } //没有回调函数 pthread_cleanup_push(pthread_mutex_unlock,&mutex);和pthread_cleanup_pop(0); //则系统将挂起在在tid2请求锁的地方. //如把注释1和注释2这两行代码不执行则child2能在child1完成取消动作前得到控制,从而顺利执行 //申请锁的操作,但可能在pthread_cond_wait(&cond,&mutex);中挂起,因为其中也有申请mutex的操作 //(因为在条件满足而离开pthread_cond_wait()前,mutex将重新被加锁,以和进入pthread_cond_wait()前的加锁动作对应!)//child1给出的是标准条件变量的使用方式:回调函数保护,等待条件前解锁, pthread_cond_wait(&cond,&mutex);返回后解锁。
时间: 2024-10-06 00:17:12