清除:
线程终止有两种情况:(1)正常终止;(2)非正常终止
(1)正常终止:线程主动调用pthread_exit或者从线程函数中return都将使线程正常退出,这是可预见的退出方式;
(2)非正常终止:线程在其他线程的干预下,或者由于自身运行出错(比如访问非法地址)而退出,这种退出方式是不可预见的。
不论是可预见的线程终止还是异常终止,都会存在资源释放的问题,如何保证线程终止时能顺利的释放掉自己所占用的资源,是一个必须考虑解决的问题。
清除:
从pthread_cleanup_push的调用点到pthread_cleanup_pop之间的程序段中的终止动作(包括调用pthread_exit()和异常终止,不包括return)都将执行
Pthread_cleanup_push()所指定的清理函数
(注意:pthread_cleanup_push和pthread_cleanup_pop是配对使用的)
#include <pthread.h>
Void pthread_cleanup_push(void(*rth)(void*),void *arg)
功能:将清除函数压入堆栈
rth : 清除函数
arg : 清除函数的参数
#include <pthread.h>
void pthread_cleanup_pop(int execute)
功能:将清除函数弹出堆栈
参数:excute 执行到pthread_cleanup_pop()时是否在弹出清理函数的同时执行该函数,excute的值为:非0:执行; 0:不执行
例程:部分
void *clean(void *arg)
{
printf("cleanup :%s \n",(char *)arg);
return (void *)0;
}
void *thr_fn1(void *arg)
{
printf("thread 1 start \n");
pthread_cleanup_push( (void*)clean,"thread 1 first handler");
pthread_cleanup_push( (void*)clean,"thread 1 second hadler");
printf("thread 1 push complete \n");
if(arg)
{
return((void *)1);
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return (void *)1;
}
void *thr_fn2(void *arg)
{
printf("thread 2 start \n");
pthread_cleanup_push( (void*)clean,"thread 2 first handler");
pthread_cleanup_push( (void*)clean,"thread 2 second handler");
printf("thread 2 push complete \n");
if(arg)
{
pthread_exit((void *)2);
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
pthread_exit((void *)2);
}
部分执行结果:
thread 2 start
thread 2 push complete
cleanup :thread 2 second handler
cleanup :thread 2 first handler
(为什么先执行cleanup :thread 2 second handler再执行cleanup :thread 2 first handler?因为:pthread_cleanup_push( (void*)clean,"thread 2 first handler"先执行先被压入堆栈,而pthread_cleanup_push( (void*)clean,"thread 2 second handler"后执行后被压入堆栈;而堆栈有“先进后出”的规则);