线程可以安排它退出时需要调用的函数,这样的函数称为线程清理处理程序,线程可以建立多个清理处理程序。处理程序记录在栈中,也就是说它们的执行顺序与它们注册时的顺序相反。它主要用来处理内存泄露,尤其是处理死锁。
pthread_cleanup_push来注册清理函数rtn,这个函数有一个参数arg。在以下三种情形之一发生时,注册的清理函数被执行:
1)调用pthread_exit。
2)作为对取消线程请求(pthread_cancel)的响应。
3)以非0参数调用pthread_cleanup_pop。
注意:
1)如果线程只是由于简单的返回而终止的,则清除函数不会被调用。
2)如果pthread_cleanup_pop被传递0参数,则清除函数不会被调用,但是会清除处于栈顶的清理函数。
名称: |
pthread_cleanup_push / pthread_cleanup_pop |
功能: |
线程清理处理程序 |
头文件: |
#include <pthread.h> |
函数原形: |
void pthread_cleanup_push(void (*rtn)(void *),void *arg); void pthread_cleanup_pop(int execute); |
参数: |
rtn 处理程序入口地址 arg 传递给处理函数的参数 |
返回值: |
无 |
测试代码如下:


1 #include<iostream> 2 #include<stdlib.h> 3 #include<pthread.h> 4 5 using std::cout; 6 using std::endl; 7 8 void cleanupA(void* arg) 9 { 10 cout << "clean " << (char*)arg << endl; 11 } 12 13 void cleanupB(void* arg) 14 { 15 cout << "clean " << (char*)arg << endl; 16 } 17 18 void* threadfun(void* arg) 19 { 20 pthread_cleanup_push(cleanupA, (void*)"A"); 21 pthread_cleanup_push(cleanupB, (void*)"B"); 22 23 int flag = 3; 24 while(flag--) 25 { 26 cout << "This is thread" << endl; 27 sleep(1); 28 } 29 30 //pthread_exit(NULL); 31 32 pthread_cleanup_pop(1); 33 pthread_cleanup_pop(1); 34 } 35 int main(int argc, char** argv) 36 { 37 pthread_t tid; 38 pthread_create(&tid, NULL, threadfun, NULL); 39 sleep(3); 40 //pthread_cancel(tid); 41 pthread_join(tid, NULL); 42 return 0; 43 }