我们最希望的就是线程在退出的时候释放其所占的所有资源,并且释放其设置的一些类似锁的资源,这就要求我们在退出线程的时候必须有收尾的操作,即线程退出时的清理
1. 清理函数
1) void pthread_cleanup_push(void (*routine) (void*), void *arg)
routine: 清理函数的函数指针
arg: 清理函数的实参
2) void pthread_cleanup_pop(int execute)
execute:弹出清理函数时是否执行, 0不执行, 非0 执行
注意点:
1. 这两个函数在同一个函数中必须成对存在
2. 清理函数得到执行的情况如下:
2. 代码举例子----线程被动取消
#include <stdio.h> #include <pthread.h> #include <unistd.h> void clean_fun(void *arg) { printf("I am a clean function\n"); return; } void *pth_fun(void *arg) { pthread_cleanup_push(clean_fun, NULL) printf("I am a pthread function\n"); while (1) { pthread_testcancel(); } pthread_cleanup_pop(0); return NULL; } int main(void) { pthread_t pth; int res = pthread_create(&pth, NULL, pth_fun, NULL); if (res) { printf("create pthread error!\n"); return 0; } sleep(3); res = pthread_cancel(pth); pthread_join(pth, NULL); printf("hello world!\n"); return 0; }
3. 线程主动结束
#include <stdio.h> #include <pthread.h> #include <unistd.h> void clean_fun(void *arg) { printf("I am a clean function\n"); return; } void *pth_fun(void *arg) { pthread_cleanup_push(clean_fun, NULL) printf("I am a pthread function\n"); pthread_exit(0); // return (void*)0; // 无法触发清理函数的执行 pthread_cleanup_pop(0); } int main(void) { pthread_t pth; int res = pthread_create(&pth, NULL, pth_fun, NULL); if (res) { printf("create pthread error!\n"); return 0; } sleep(3); //pthread_join(pth, NULL); printf("hello world!\n"); return 0; }
原文:https://www.cnblogs.com/victor1234/p/14680890.html