由于存在线程可能会因为一些异常情况终止执行,从而导致它的一些资源得不到释放。需要一个机制来简化资源释放的编程。
调用pthread_cleanup_push()来压入清理函数栈,多次调用形成一个函数链,在执行时与压栈的相反顺序弹出。
只有一下几种情况注册清理函数才被执行:
1)调用pthread_exit。
2)作为对取消线程请求(pthread_cancel)的响应。
3)以非0参数调用pthread_cleanup_pop。
用法:
#include <pthread.h>
void pthread_cleanup_push(void (*rtn)(void *),void *arg);
注意:
1)如果线程只是由于简单的返回而终止的,则清除函数不会被调用。
2)如果pthread_cleanup_pop被传递0参数,则清除函数不会被调用,但是会清除处于栈顶的清理函数。
例子
#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);
}