线程的处理函数pthread_cleanup_push/pthread_cleanup_pop

由于存在线程可能会因为一些异常情况终止执行,从而导致它的一些资源得不到释放。需要一个机制来简化资源释放的编程。

调用pthread_cleanup_push()来压入清理函数栈,多次调用形成一个函数链,在执行时与压栈的相反顺序弹出。

只有一下几种情况注册清理函数才被执行:

   1)调用pthread_exit。
   2)作为对取消线程请求(pthread_cancel)的响应。
   3)以非0参数调用pthread_cleanup_pop。

 

用法:

#include <pthread.h>

void pthread_cleanup_push(void (*rtn)(void *),void *arg);

 

注意:

1)如果线程只是由于简单的返回而终止的,则清除函数不会被调用。

2)如果pthread_cleanup_pop被传递0参数,则清除函数不会被调用,但是会清除处于栈顶的清理函数。

 

例子

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <pthread.h>
       
void cleanup()
{
    printf("clean up\n");
}
void *test_cancel(void)
{
     pthread_cleanup_push(cleanup,NULL);
     printf("test clean up\n");
     while(1)
     {
           printf("test message\n");
       sleep(1);
     }
     pthread_cleanup_pop(1);
}

int main(int argc,char *argv[])
   
{
     pthread_t tid;
     pthread_create(&tid,NULL,(void *)test_cancel,NULL);
     sleep(5);
     pthread_cancel(tid);
     pthread_join(tid,NULL);
}

转载于:https://my.oschina.net/u/919373/blog/149702

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值