因为存在线程可能会由于一些异常状况终止执行,从而致使它的一些资源得不到释放。须要一个机制来简化资源释放的编程。 编程
调用pthread_cleanup_push()来压入清理函数栈,屡次调用造成一个函数链,在执行时与压栈的相反顺序弹出。 函数
只有一下几种状况注册清理函数才被执行: spa
1)调用pthread_exit。
2)做为对取消线程请求(pthread_cancel)的响应。
3)以非0参数调用pthread_cleanup_pop。 线程
用法: 资源
#include <pthread.h> string
void pthread_cleanup_push(void (*rtn)(void *),void *arg); it
注意: io
1)若是线程只是因为简单的返回而终止的,则清除函数不会被调用。 thread
2)若是pthread_cleanup_pop被传递0参数,则清除函数不会被调用,可是会清除处于栈顶的清理函数。 test
例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <pthread.h>
void cleanup()
{
printf("clean up\n");
}
void *test_cancel(void)
{
pthread_cleanup_push(cleanup,NULL);
printf("test clean up\n");
while(1)
{
printf("test message\n");
sleep(1);
}
pthread_cleanup_pop(1);
}
int main(int argc,char *argv[]) { pthread_t tid; pthread_create(&tid,NULL,(void *)test_cancel,NULL); sleep(5); pthread_cancel(tid); pthread_join(tid,NULL); }