ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

linux--(2)线程的清理

2021-12-02 09:35:01  阅读:178  来源: 互联网

标签:execute 函数 -- void linux cleanup 线程 pthread


线程的清理函数

类似于进程的终止函数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

 

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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有