Linux 多线程开发-等待线程结束pthread_join

1、函数原型

int pthread_join(pthread_t pid, void **value_ptr);
  1. pid:所等待的线程ID;
  2. value_ptr:通常设置为NULL,如果不为NULL,pthread_join将复制一份线程退出值到一个内存区域,并让*value_ptr指向该内存。
  3. 返回值:执行成功返回0,否则返回错误码。

2、作用

pthread_creat创建完成子线程后,主线程与子线程并行执行,用pthread_join可以让主线程等待子线程结束后再继续执行。

pthread_join用于等待子线程执行结束,即子线程函数执行完毕才会返回,会一直阻塞。

主线程调用pthread_join后,主线程会挂起,让出CPU直到该子线程执行结束。调用pthread_join让子线程执行结束后,子线程资源会自动释放。

3、示例

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

void thread_func(void)
{
    int i;
    for(i = 0; i < 3; i++){
        printf("thread cur cnt:%d\n",i);
    }
    printf("thread_func exit\n");
    return;
}
int main(int argc,char *argv[])
{
    pthread_t thrid;
    int ret;
    
    ret = thread_creat(&thrid,NULL,(void *(*)(void *))thread_func,NULL);
    if(ret){
        printf("pthread creat error:%d\n",ret);
        return -1;
    }
    pthread_join(thrid,NULL);
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值