pthread_detach函数

1,函数的声明:

int pthread_detach(pthread_t thread);

2,函数的返回值
成功:0;失败:错误号

3,作用:

从状态上实现线程分离

4,线程分离状态:
指定该状态,线程主动与主控线程断开关系。线程结束后(不会产生僵尸线程),其退出状态不由其他线程获取,而直接自己自动释放(自己清理掉PCB的残留资源)进程结束后,线程也会结束。网络、多线程服务器常用。

5,使用pthread_detach函数实现线程分离

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
 
void *tfn(void *arg)
{
        int n = 3;
 
        while (n--) {
                printf("thread count %d\n", n);
                sleep(1);
        }
 
        //return (void *)1;
    pthread_exit((void *)1);
}
 
int main(void)
{
        pthread_t tid;
        void *tret;
        int err;
 
#if 0
 
        pthread_attr_t attr;            /*通过线程属性来设置游离态(分离态)*/
        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
        pthread_create(&tid, &attr, tfn, NULL);
 
#else
 
        pthread_create(&tid, NULL, tfn, NULL);
        pthread_detach(tid);         //让线程分离  ----自动退出,无系统残留资源
 
#endif
 
        while (1) {
                err = pthread_join(tid, &tret);
        printf("-------------err= %d\n", err);
                if (err != 0)
                        fprintf(stderr, "thread_join error: %s\n", strerror(err));
                else
                        fprintf(stderr, "thread exit code %d\n", (int)tret);
 
                sleep(1);
        }
 
        return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路漫漫其远,吾求索

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值