linux回调函数的使用

#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 
");
  printf("thread1 pthread_mutex_lock returns %d
",pthread_mutex_lock(&mutex));
  pthread_cond_wait(&cond,&mutex);
  printf("thread1 condition applied
");
  pthread_mutex_unlock(&mutex);
  sleep(5);
  }
 pthread_cleanup_pop(0);//注释2
}
void *child2 (void *arg)
{
 while(1)
 {sleep(3);//注释3
  printf("thread2 get running 
");
  printf("thread2 pthread_mutex_lock returns %d
",pthread_mutex_lock(&mutex));
  pthread_cond_wait(&cond,&mutex);
  printf("thread2 condition applied
");
  pthread_mutex_unlock(&mutex);
  sleep(1);
  }
}
int main()
{pthread_t tid1,tid2;
 printf("hello condition variable test
");
 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()很可能引起死锁!!

程序运行结果为:

可以看出最后一直在执行线程2,因为线程1被取消了!                         这就是要加-lpthread的原因!!
原文地址:https://www.cnblogs.com/leijiangtao/p/4156089.html