37.1 线程清理和控制函数
#include <pthread.h> void pthread_cleanup_push(void (* rtn)(void *), void *arg);
void pthread_cleanup_pop(int execute);
- 函数参数
- rtn:清理函数指针
- arg:调用清理函数传递的参数
- execute:值 1 时,执行线程清理函数;值 0 时,不执行线程清理函数
- 返回值
- 成功,返回 0;否则,返回错误编号
- 触发线程调用清理函数的工作
- 调用 pthread_exit
- 响应取消请求
- 用非零 execute 参数调用 thread_cleanup_pop 时
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> /** 定义线程清理函数 */
void clean_fun(void *arg)
{
char *s = (char *)arg;
printf("clean_fun: %s\n", s);
} void *th_fun(void *arg)
{
int execute = (int )arg; pthread_cleanup_push(clean_fun, "first clean func");
pthread_cleanup_push(clean_fun, "second clean func");
printf("thread running %lx\n", pthread_self()); pthread_cleanup_pop(execute);
pthread_cleanup_pop(execute);
return (void *);
} int main(void)
{
int err;
pthread_t th1, th2; if((err = pthread_create(&th1, NULL, th_fun, (void *))) != ) {
perror("pthread create error");
} pthread_join(th1, NULL);
printf("th1(%lx) finished\n", th1); if((err = pthread_create(&th2, NULL, th_fun, (void *))) != ) {
perror("pthread create error");
} pthread_join(th2, NULL);
printf("th2(%lx) finished\n", th2); return ;
}
运行如下:
线程结束,会触发调用最终的 clean 函数,调用的时候会根据 pop 里面的入栈顺序,先入后出进行调用。