函数原型:
#include
void pthread_cleanup_push(void (*rtn)(void *),void *arg);
函数rtn是清理函数,arg是调用参数
void pthread_cleanup_pop(int execute);
在前面讲过线程的终止方式,是正常终止还是非正常终止,都会存在一个资源释放的问题,在posix中提供了一组,就是我们上面看的函数进行线程退出的处理函数,有些像在进程中的atexit函数。释放的方式是指pthread_cleanup_push的调用点到pthread_cleanup_pop之间程序段进行终止。
pthread_cleanup_push()/pthread_cleanup_pop采用先入后出的方式的栈的管理方式,void *rtn(void *),在执行pthread_cleanup_push()时压入函数栈,多次执行pthread_cleanup_push()形成一个函数链,在执行这个函数链的时候会以反方向弹出,即先入后出。execute参数表识,是否执行弹出清理函数,当execute=0时不进行弹出清理函数,非零的时候弹出处理函数。
例程9
程序目的:实现在正常结束线程的时候,进行函数处理
程序名称:pthread_clean.c
/********************************************************************************************
** Name:pthread_clean.c
** Used to study the multithread programming in Linux OS
** A example showing a thread to be cleaned.
** Author:zeickey
** Date:2008/6/28
** Copyright (c) 2006,All Rights Reserved!
*********************************************************************************************/
#include
#include
#include
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);
}
int main(void)
{
int err;
pthread_t tid1,tid2;
void *tret;
err=pthread_create(&tid1,NULL,thr_fn1,(void *)1);
if(err!=0)
{
printf("error .... \n");
return -1;
}
err=pthread_create(&tid2,NULL,thr_fn2,(void *)1);
if(err!=0)
{
printf("error .... \n");
return -1;
}
err=pthread_join(tid1,&tret);
if(err!=0)
{
printf("error .... \n");
return -1;
}
printf("thread 1 exit code %d \n",(int)tret);
err=pthread_join(tid2,&tret);
if(err!=0)
{
printf("error .... ");
return -1;
}
printf("thread 2 exit code %d \n",(int)tret);
return 1;
}
编译方法:
gcc -Wall -lpthread pthread_clean.c
执行结果:
thread 1 start
thread 1 push complete
thread 1 exit code 1
thread 2 start
thread 2 push complete
cleanup :thread 2 second handler
cleanup :thread 2 first handler
thread 2 exit code 2
阅读(382) | 评论(0) | 转发(0) |