1.线程清理和控制
#include<pthread.h>
void pthread_cleanup_push(void (*rtn)(void*),void* arg);
void pthread_cleanup_pop(int execute);
返回:成功返回0,否则返回错误编号
这个是一组是成对出现的
- 参数
- rtn:用户定义的清理函数指针
- arg:调用清理函数传递的参数
- execute:值1时执行线程清理函数,值为0不执行线程清理函数
- 触发线程调用清理函数的动作 有三种情况
- 调用pthread_exit
- 响应取消请求— 进程中的其他线程调用pthread_cancel此线程被取消了
- 用非零execute参数调用pthread_cleanup_pop时
#include<pthread.h>
#include<stdlib.h>
#include<stdio.h>
//定义线程清理函数
void clean_fun(void *arg){
char *s = (char*)arg;
printf("clean_func: %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("threadd running %ls\n",pthread_self());
pthread_cleanup_pop(execute);
pthread_cleanup_pop(execute);
return (void*)0;
}
int main(void){
int err;
pthread_t th1,th2;
if((err = pthread_create(&th1,null,th_fun,(void*)1)!=0){
printf("pthread create error");
}
pthread_join(th1,null);
printf("th1(%lx) finished\n",th1);
if((err = pthread_create(&th2,null,th_fun,(void*)1)!=0){
printf("pthread create error");
}
pthread_join(th2,null);
printf("th2(%lx) finished\n",th2);
}
代码运行结果:
id((err = pthread_create(&th1,null,th_fun,(void*)0)!=0){
printf("pthread create error");
}//当传入参数是0是 不调用线程清理函数
/*
此时th1线程只运行了printf("threadd running %ls\n",pthread_self());和printf("th1(%lx) finished\n",th1);两个输出语句,没有运行线程清理函数中的输出语句,th2线程运行了线程清理函数
和
*/
2.线程和进程的 启动和终止的 比较
进程 | 线程 |
---|---|
fork() | pthread_create() |
return/exit()/_exit() | return/pthread_exit() |
wait() | pthread_join() |
atexit() | pthread_clean_push/pthread_clean_pop() |