简介
清理函数和控制函数
这一对一般是成对出现的
#include <pthread.h>
void pthread_cleanup_push(void (routine)(void ),void *arg);
参数:
routine: 清理函数指针
arg: 调用清理函数传递的参数
void pthread_cleanup_pop(int execute);
参数:
execute:值1时执行清理函数,值0时不执行线程清理函数.
触发线程调用清理函数的动作
1)调用pthread_exit
2)相应取消请求
3)用非零execute参数调用pthread_cleanup_pop时
实例代码
1 | #include <pthread.h> |
输出:1
2
3
4
5
6
7
8th_func run, execute:0
thead running 7ff10e7b5700
tid1(7ff10e7b5700) finished
th_func run, execute:1
thead running 7ff10e7b5700
run clean up func second clean up
run clean up func first clean up
tid2(7ff10e7b5700) finished
在输出中,可以看出execute为0时,清理函数不执行,execute为1时,清理函数会被执行.
进程,线程启动和终止方式分比较
|进程 |线程 |
|:--------:|:--------:|
|fork() |pthread_create |
|reture/exit()/_exit() |return/pthread_exit()|
|wait() |pthread_join() |
|atexit() |pthread_cleanup_push()/pthread_cleanup_pop()|