系统相关
首页 > 系统相关> > linux--(2)线程的清理

linux--(2)线程的清理

作者:互联网

线程的清理函数

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

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

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

 

案例:

#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

 

标签:execute,函数,--,void,linux,cleanup,线程,pthread
来源: https://www.cnblogs.com/halfup/p/15631736.html