linux——线程设置分离属性

通过属性设置线程的分离

1.线程属性类型: pthread_attr_t attr;

2.线程属性操作函数:

对线程属性变量的初始化

int pthread_attr_init(pthread_attr_t* attr);

设置线程分离属性

int pthread_attr_setdetachstate( pthread_attr_t* attr, int detachstate );

参数: attr : 线程属性

detachstate

PTHREAD_CREATE_DETACHED(分离)

PTHREAD_CREATE_JOINABLE(非分离)

释放线程资源函数

int pthread_attr_destroy(pthread_attr_t* attr);

复制代码
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>
void* myfunc(void *arg)
{
        printf("child pthread id:%ld\n",pthread_self());
        return 0;
}
int main()
{
        pthread_t pthid;
        int ret;
        //init attr
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        //set attr
        pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

        ret = pthread_create(&pthid,&attr,myfunc,NULL);
        if(ret != 0)
        {
                printf("error number is %d\n",ret);
                printf("%s\n",strerror(ret));
        }
        printf("parent pthread id:%ld\n",pthread_self());

        for(int i=0;i<5;i++)
        {
                printf("i=%d\n",i);
        }
        sleep(2);
        pthread_attr_destroy(&attr);
        return 0;
}

这段代码就是创建一个分离线程,主线程不用等它,他自己跑完自动回收资源,不需要pthread_join。

也可以用pthred_detach(pthid),就属于创建后将普通线程修改为分离线程,效果是一样的

复制代码
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>

void* myfunc(void *arg)
{
    printf("child pthread id:%ld\n",pthread_self());
    return NULL;
}

int main()
{
    pthread_t pthid;
    int ret;

    
    ret = pthread_create(&pthid,NULL,myfunc,NULL);
    if(ret != 0)
    {
        printf("error:%d %s\n",ret,strerror(ret));
    }

    // 创建完立刻设为分离态
    pthread_detach(pthid);  

    printf("parent pthread id:%ld\n",pthread_self());
    for(int i=0;i<5;i++){ printf("i=%d\n",i); }

    sleep(2);

    return 0;
}

两种方法都可以,完全等价。

相关推荐
一直会游泳的小猫6 小时前
homebrew
linux·mac·工具·包管理
寒秋花开曾相惜6 小时前
(学习笔记)4.2 逻辑设计和硬件控制语言HCL(4.2.1 逻辑门&4.2.2 组合电路和HCL布尔表达式)
linux·网络·数据结构·笔记·学习·fpga开发
狂奔的sherry6 小时前
一次由 mount 引发的 Linux 文件系统“错觉”
linux·运维·服务器
小黑要努力6 小时前
智能音箱遇到的问题(一)
linux·运维·git
ch3nyuyu7 小时前
静态库和动态库的制作
linux·运维·开发语言
一口Linux7 小时前
Linux C编程 | 从0实现telnet获取程序终端控制权
linux·运维·c语言
willhuo7 小时前
Certbot工具在CentOS 7.9上申请和配置SSL证书完整教程
linux·centos·ssl
zhangrelay8 小时前
三分钟云课实践速通--大学物理--python 版
linux·开发语言·python·学习·ubuntu·lubuntu
风翼靓崽9 小时前
linux命令杂记 - 杂乱无章
linux·运维·服务器
handler019 小时前
Linux 进程探索:从 PCB 管理到 fork() 的写时拷贝
linux·c语言·c++·笔记·学习