pthread_detach函数_pthread detach函数

收集整理了一份《2024年最新物联网嵌入式全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升的朋友。
img
img

如果你需要这些资料,可以戳这里获取

需要这些体系化资料的朋友,可以加我V获取:vip1024c (备注嵌入式)

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人

都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

代码如下:

#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;

//线程执行函数
void *mythread(void *arg)
{
        cout << "child thread, pid==" << getpid() << ", id==" << pthread_self() << endl;
        sleep(10);
}

int main()
{
        //int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    //                      void *(*start_routine) (void *), void *arg);
        //创建子线程
        pthread_t thread;
        int ret = pthread_create(&thread, NULL, mythread, NULL);
        if(ret!=0)
        {
                cout << "pthread_create error, " << strerror(ret) << endl;
                return -1;
        }
        cout << "main thread, pid==" << getpid() << ", id==" << pthread_self() << endl;

        //设置线程为分离属性
        pthread_detach(thread);

        //子线程设置分离属性,则pthread_join不再阻塞,立刻返回
        ret = pthread_join(thread, NULL);
        if(ret!=0)
        {

                cout << "pthread_join error, " << strerror(ret) << endl;
        }

        //目的是为了让子线程能够执行起来
        sleep(1);
        return 0;
}

也可以利用pthread_create的第二个参数设置分离属性,部分核心代码如下:

int main()
{
        //定义pthread_attr_t类型的变量
        pthread_attr_t attr;

        //初始化attr变量
        pthread_attr_init(&attr);

        //设置attr为分离属性
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

        //创建子线程
        pthread_t thread;
        int ret = pthread_create(&thread, &attr, mythread, NULL);
        if(ret!=0)
        {
                cout << "pthread_create error, " << strerror(ret) << endl;
                return -1;
        }
        cout << "main thread, pid==" << getpid() << ", id==" << pthread_self() << endl;



**收集整理了一份《2024年最新物联网嵌入式全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升的朋友。**
![img](https://img-blog.csdnimg.cn/img_convert/93115576481616a1157b55e1ab8a9777.png)
![img](https://img-blog.csdnimg.cn/img_convert/c8e99130bf2a426b0c331ce71ad51f8a.png)

**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618679757)**

**需要这些体系化资料的朋友,可以加我V获取:vip1024c (备注嵌入式)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人**

**都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

*一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人**

**都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值