pthread_cleanup_push是用于当线程退出时,让保证其有机会释放资源的一种手段.注意: pthread_cleanup_push必须和pthread_cleanup_pop一起使用,具体原因在于在pthread.h中,通过macro define的方式,使得常量进行数据展开.
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void
cleanup(void *arg)
{
fprintf(stderr,"clean up called : argument %s\n",(char*)arg);
}
void *
mythread(void *arg)
{
pthread_cleanup_push(cleanup,(void*)("mythread argument"));
fprintf(stderr,"mythread before usleep\n");
usleep(1000*1000*60);
fprintf(stderr,"mythread after usleep\n");
pthread_cleanup_pop(0); //这里如果没有搭配使用pthread_cleanup_pop,则会编译报错,main.cpp:22:5: error: expected ‘while’ before ‘main’ main.cpp:22:5: error: expected ‘(’ before ‘main’
return (void*)0;
}
int main(int argc, char *argv[])
{
pthread_t pid;
pthread_create(&pid,0,mythread,0);
usleep(1000*1000);
//pthread_cancel (pid);
usleep(1000*1000);
return 0;
}
[转载]
pthread_cleanup_push与pthread_cleanup_pop的目的(作用)是什么
比如thread1:
执行pthread_mutex_unlock(&mutex);
这个例子中,如果线程1执行accept时,线程会阻塞(也就是等在那里,有客户端连接的时候才返回,或则出现其他故障),线程等待中......
这时候线程2发现线程1等了很久,不赖烦了,他想关掉线程1,于是调用pthread_cancel()或者类似函数,请求线程1立即退出。这时候线程1仍然在accept等待中,当它收到线程2的cancel信号后,就会从accept中退出,然后终止线程,注意这个时候线程1还没有执行:
pthread_mutex_unlock(&mutex);
也就是说锁资源没有释放,这回造成其他线程的死锁问题。pthread_cleanup_push注册一个回调函数,如果你的线程在对应的pthread_cleanup_pop之前异常退出(return是正常退出,其他是异常),那么系统就会执行这个回调函数(回调函数要做什么你自己决定)。但是如果在pthread_cleanup_pop之前没有异常退出,pthread_cleanup_pop就把对应的回调函数取消了,