多线程使用基础篇(三) pthread_detach()的其它用法

以下举例代码pthread_detach函数通过另外两种方式回收对应线程结束的资源。

#include <stdio.h>
#include <pthread.h>
void *ptha_func(void * arg){
    printf("ptha_func.....\n");
    return NULL;
}
void *pthb_func(void * arg){
    printf("pthb_func.....\n");
     //pthread_self()函数获取当前线程id号,
    //pthread_detach()函数等待当前线程id号对应线程结束,回收线程资源。
    pthread_detach(pthread_self());
    return NULL;
}
void *pthc_func(void * arg){
    printf("pthc_func.....\n");
    return NULL;
}
int main(void){
    pthread_t ptida,ptidb,ptidc;
    pthread_create(&ptida,NULL,ptha_func,NULL);
    pthread_create(&ptidb,NULL,pthb_func,NULL);
    pthread_create(&ptidc,NULL,pthc_func,NULL);
    //将ptidc线程号设置为detached state状态
    pthread_detach(ptidc);
    printf("ptida pthread_join return value:%d\n",\
            pthread_join(ptida,NULL));
    printf("ptidb pthread_join return value:%d\n",\
            pthread_join(ptidb,NULL));
    printf("ptidc pthread_join return value:%d\n",\
            pthread_join(ptidc,NULL));
    return 0;
}

执行结果:

pthread$gcc pth_detach_other.c -lpthread
pthread$./a.out 
ptha_func.....
pthb_func.....
pthc_func.....
ptida pthread_join return value:0
ptidb pthread_join return value:22
ptidc pthread_join return value:22

通过上述执行结果可以看出:
线程ptida执行结束后;由pthread_join函数回收线程资源。
线程ptidb和ptidc执行结束后;由pthread_detach函数回收线程资源。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值