Linux 线程清理和控制函数

简介

清理函数和控制函数

这一对一般是成对出现的

#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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

void clean_up(void *arg)
{
char *a = (char *)arg;
printf("run clean up func %s\n", a);
}

void *th_func(void *args)
{
int execute = (int)args; //因为传进来的就是1;
printf("th_func run, execute:%d\n", execute);
pthread_cleanup_push(clean_up, "first clean up");
pthread_cleanup_push(clean_up, "second clean up");
printf("thead running %lx\n", pthread_self());
pthread_cleanup_pop(execute);
pthread_cleanup_pop(execute); //push 和 pop 要成对出现
return (void *)0;
}

int main(int argc, char *args[])
{
int err;
pthread_t tid1, tid2;

if((err = pthread_create(&tid1, NULL, th_func, (void *)0)) != 0)
{
perror("create pthread error:");
return err;
}
pthread_join(tid1, NULL);
printf("tid1(%lx) finished\n", tid1);

if((err = pthread_create(&tid2, NULL, th_func, (void *)1)) != 0)
{
perror("create pthread error:");
return err;
}
pthread_join(tid2, NULL);
printf("tid2(%lx) finished\n", tid2);
return 0;
}

输出:

1
2
3
4
5
6
7
8
th_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()|