linux--(2)线程的清理

线程的清理函数

类似于进程的终止函数atexit()。

include <pthread.h>
void pthread_cleanup_push( void (*rtn)(void*), void* arg);
void pthread_cleanup_pop(int execute);

以上一组代码是成对出现的,具体执行可写成:
while(execute)
{ //执行线程处理函数 
}

 

  • 参数
    • rtn:清理函数的指针,清理函数也是自己定义的函数
    • arg:调用清理函数传递的参数
    • execute:值为1时执行线程清理函数,值为0时不执行线程清理函数
  • 触发线程调用清理函数的动作
    • 调用pthread_exit
    • 响应取消请求,其他线程调用cancel
    • 用非0 execute参数调用pthread_cleanup_pop时

案例:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.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; //execute为1时会调用清理函数
    pthread_cleanup_push(clean_fun, "first clean func\n"); //线程处理函数  参数
    pthread_cleanup_push(clean_fun, "second clean func\n");
    printf("thread running %lx\n",pthread_self());
    pthread_cleanup_pop(execute);//push 与 pop一组
    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*)0)!=0)) //th1传进去0 ,不执行清理函数
   {perror("pthread_create error");}
    pthread_join(th1,NULL);
    printf("th1(%lx) finished\n",th1);
    

    if((err=pthread_create(&th2,NULL,
                         th_fun,(void*)1)!=0))
   {perror("pthread_create error");}
    pthread_join(th2,NULL);
    printf("th2(%lx) finished\n",th2);
}

 

 

 //先压的后执行,后压的先执行,所以先second再 first

 

posted @ 2021-12-02 09:14  halfup  阅读(230)  评论(0编辑  收藏  举报