关于pthread_detach

前几天看了APUE关于线程部分的内容,这部分介绍的比较少没太理解,再回头看的时候有点感悟,特此记录下来。

函数原型

#include <pthread.h>
int pthread_detach(pthread_t tid); //成功返回0;出错返回错误编号

功能说明

创建一个线程默认的状态是joinable, 如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码),所以创建线程者应该pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源。

实例分析

int
main(void)
{
    int       err ;
    pthread_t tid ;

    //创建线程
    if ((err = pthread_create(&tidbuf[0], NULL, thr1, NULL)) != 0)
        perror("can't create thread!\n") ;
    if ((err = pthread_create(&tidbuf[1], NULL, thr2, NULL)) != 0)
        perror("can't create thread!\n") ;


    //等待线程结束
    pthread_join(tidbuf[0], NULL) ;
    pthread_join(tidbuf[1], NULL) ;

    exit(0) ;
}

在这种情况下,主线程会阻塞等待两个线程结束回收其资源

int
main(void)
{
    int       err ;
    pthread_t tid ;

    //创建线程
    if ((err = pthread_create(&tidbuf[0], NULL, thr1, NULL)) != 0)
        perror("can't create thread!\n") ;
    if ((err = pthread_create(&tidbuf[1], NULL, thr2, NULL)) != 0)
        perror("can't create thread!\n") ;


    //非阻塞,可立即返回
    pthread_detach(tidbuf[0]) ;
    pthread_detach(tidbuf[1]) ;

    exit(0) ;
}

这将该子线程的状态设置为detached,则该线程运行结束后会自动释放所有资源。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值