1.介绍
pthread_cleanup_push
和pthread_cleanup_pop
函数是POSIX线程库中的两个函数,它们一起用于定义一个清理处理程序。当线程终止时,无论是因为线程自然结束、通过pthread_cancel
被其他线程取消,或者是调用pthread_exit
自我结束,都会执行清理处理程序。
void pthread_cleanup_push(void (*routine) (void *), void *arg);
void pthread_cleanup_pop(int execute);
-
pthread_cleanup_push
函数用于推送一个清理处理程序到当前线程的清理处理程序栈上。这个清理处理程序由routine
参数指定,当线程终止时,将以arg
为参数调用这个函数。 -
pthread_cleanup_pop
函数用于弹出当前线程的清理处理程序栈顶的清理处理程序。如果execute
参数非零,那么在弹出清理处理程序之前会执行它。
这两个函数必须在同一层次的代码块内成对出现,而且pthread_cleanup_push
函数的左括号与配对的pthread_cleanup_pop
函数的右括号之间不能有其他的左右括号配对。也就是说,它们要在同一个作用域中。这一点在某些编译器中很重要,因为这两个函数可能是以宏的形式实现的。
2.例子
#include <stdio.h>
#include <pthread.h>
void cleanup(void *arg) {
printf("Cleaning up: %s\n", (char*)arg);
}
void* thread_func(void *arg) {
pthread_cleanup_push(cleanup, "First handler");
pthread_cleanup_push(cleanup, "Second handler");
printf("Thread running.\n");
// 如果参数为0,则在pthread_cleanup_pop调用时不执行清理处理程序,只将其从清理栈中删除
// 如果参数非0,则在pthread_cleanup_pop调用时执行清理处理程序,然后再将其从清理栈中删除
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);
pthread_join(thread, NULL);
return 0;
}
需要注意对于线程相关代码的编译需要链接上posix线程库:gcc xxx.c -lpthread -l是链接选项,pthread是库名称,默认不添加空格也可以添加空格gcc xxx.c -l pthread