linux的pthread_join函数

这里写目录标题

pthread_join函数

int pthread_join(pthread_t pthread, void *retval)
参数:
pthread:要回收的子线程的ID
retval:读取线程退出的携带信息
传出参数
void
ptr;
pthread_join(pthid,&ptr);
指向的内存和pthread_exit参数指向地址一致

代码

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

void *pthread1(void * arc)
{
        printf("pthread1 is running\n");
        printf("pthread1 id is %ld",pthread_self());
        pthread_exit("pthread is exit\n");
}
void main()
{
        pthread_t id;

        pthread_create(&id,NULL,pthread1,NULL);
        printf("main pthread is %ld\n",pthread_self());
        void * ptr=NULL;
        pthread_join(id,&ptr);
        printf("join : ptr is %s\n",(char *)ptr);
        int i=0;
        while(i<10)
        {
                printf("main pthread  is running %d\n",i);
                i++;
                sleep(1);

        }

}
~ 

执行结果

请添加图片描述

注意的一些细节:
函数原型: void pthread‐exit(void *retval);
retval指针:必须指向全局,堆,静态变量
如果该代码改成:

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

void *pthread1(void * arc)
{
        printf("pthread1 is running\n");
        printf("pthread1 id is %ld\n",pthread_self());
        int num=10;
        //pthread_exit("pthread is exit\n");
        pthread_exit((void * )&num);
}
void main()
{
        pthread_t id;

        pthread_create(&id,NULL,pthread1,NULL);
        printf("main pthread is %ld\n",pthread_self());
        //void * ptr=NULL;
        //pthread_join(id,&ptr);
        //printf("join : ptr is %s\n",(char *)ptr);
        void * ptr=NULL;
        pthread_join(id,&ptr);
        printf("join : ptr is %d\n",*(int *)ptr);
        int i=0;
        while(i<10)
        {
                printf("main pthread  is running %d\n",i);
                i++;
                sleep(1);

        }

}

执行结果:
请添加图片描述
可以看到这里ptr不是10
请添加图片描述
这是因为这里的num是存放在栈区的,所以会出现错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值