1.pthread_cleanup_push
- 功能:清理函数
- 原型:
void pthread_cleanup_push(void (*routine)(void *), void * arg);
- 参数:
1)void (*routine) (void*)
执行:
a.显式调用:pthread_exit
b.线程被取消:pthread_cancel
c.清理处理函数被弹出:pthread_cleanup_pop(1),\会立刻执行相应的清理函数,但线程暂未被终止,直到 pthread_exit() 或 start_routine 返回
2)void* args - 返回值:
无返回值
2.pthread_cleanup_pop
- 功能:清理函数
- 原型:
void pthread_cleanup_pop(int execute);
- 参数:
1)int execute:0,不执行;非0,执行 - 返回值:
无返回值
执行时机:
1)调用 pthread_exit()
2)响应取消请求
3)调用 pthread_cleanup_pop(1),不会导致线程终止
注意事项:
1)从 start_routine 正常返回,不会执行线程清理函数(不会被自动调用,例:return NULL;)
2)pthread_cleanup_push 和 pthread_cleanup_pop 必须成对出现
DO
#include <func.h>
void cleanup(void* args) {
char* msg = (char*) args;
printf("cleanup: %s\n", msg);
}
void* start_routine(void* args) {
// 注册线程清理函数
pthread_cleanup_push(cleanup, "first");
pthread_cleanup_push(cleanup, "second");
pthread_cleanup_push(cleanup, "third");
// pthread_cleanup_pop(1);
// pthread_cleanup_pop(0);
sleep(2);
printf("thread1: I'm going to die...\n");
pthread_exit(NULL); // 子线程退出
// return NULL;
// while (1) {
// pthread_testcancel();
// }
// 后面的代码肯定不会被执行
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
}
int main(int argc, char* argv[])
{
pthread_t tid;
int err;
err = pthread_create(&tid, NULL, start_routine, NULL);
if (err) {
error(1, err, "pthread_create");
}
sleep(3);
pthread_cancel(tid); // 给tid发送取消请求
// 等待子线程结束
err = pthread_join(tid, NULL);
if (err) {
error(1, err, "pthread_join %lu", tid);
}
return 0;
}