补充:线程分离态

pthread_detach

pthread_t tid:分离线程tid
返回值:成功返回0,失败返回错误号。

一般情况下,线程终止后,其终止状态一直保留到其它线程调用pthread_join获取
它的状态为止。但是线程也可以被置为detach状态,这样的线程一旦终止就立刻回收
它占用的所有资源,而不保留终止状态。

不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL。

如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。

小实例

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>

void *thr_fn(void *arg){
    int n=3;
    while(n--){
        printf("thread count %d\n",n);
        sleep(1);
    }
    return (void*)1;
}

int main(void){
    pthread_t tid;
    void *tret;
    int err;
    pthread_create(&tid,NULL,thr_fn,NULL);
    //第一次运行时注释掉下面这行,第二次再打开,分析两次结果
    pthread_detach(tid);
    while(1){
        err=pthread_join(tid,&tret);
        if(err!=0){
            fprintf(stderr,"thread %s\n",strerror(err));
        }else{
            fprintf(stderr,"thread exit code %ld\n",(long)tret);
        }
        sleep(1);
    }
    return 0;
}

第一次:

 

 第二次:

因为已经detach,所以tid无效,无法join

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值