关于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,则该线程运行结束后会自动释放所有资源。

pthread_detach函数用于将一个线程设置为分离状态。当一个线程处于分离状态时,该线程终止时底层资源会立即被回收,不会占用系统资源。另外,分离状态的线程无法被其他线程使用pthread_join函数获取其退出状态。 pthread_detach(threadid)函数的功能是使线程ID为threadid的线程处于分离状态。一旦线程处于分离状态,该线程终止时底层资源立即被回收。通常在主线程使用pthread_create()创建子线程后,可以调用pthread_detach(threadid)将刚刚创建的子线程设置为分离状态,这样可以确保子线程的资源会被及时释放。而且,子线程也可以自己分离自己,通过调用pthread_detach(pthread_self())来实现自身的分离。因为pthread_self()函数返回的是调用它的线程的线程ID。 总结一下,pthread_detach函数用于将线程设置为分离状态,使其在终止时立即释放资源,不再占用系统资源。而pthread_detach(threadid)和pthread_detach(pthread_self())是实现线程分离的两种方式,分别是将指定线程和自身线程设置为分离状态。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [linux中pthread_join()与pthread_detach()详解](https://blog.csdn.net/weibo1230123/article/details/81410241)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值