c主线程如何等待子线程结束 linux_Linux多线程(二)(线程等待,退出)

本文详细介绍了在Linux环境中,主线程如何通过`pthread_join`等待子线程结束,以及子线程资源的释放问题。通过示例代码展示了`pthread_join`函数的使用,解释了其阻塞特性以及如何获取子线程返回值。同时,讨论了线程取消和使用`pthread_cleanup_push`、`pthread_cleanup_pop`进行资源清理的方法。
摘要由CSDN通过智能技术生成

1.1. 等待线程退出

线程从入口点函数自然返回,或者主动调用pthread_exit()函数,都可以让线程正常终止

线程从入口点函数自然返回时,函数返回值可以被其它线程用pthread_join函数获取

pthread_join原型为:

#include

int pthread_join(pthread_t th, void **thread_return);

1. 该函数是一个阻塞函数,一直等到参数th指定的线程返回;与多进程中的wait或waitpid类似。

thread_return是一个传出参数,接收线程函数的返回值。如果线程通过调用pthread_exit()终止,则pthread_exit()中的参数相当于自然返回值,照样可以被其它线程用pthread_join获取到。

Example:返回值的例子

#include

#include

#include

void *ThreadFunc(void *pArg)

{

int iArg = (int)pArg; //将void*转换为int

sleep(iArg);

if(iArg < 3)

return (void *)(iArg*2);

else

pthread_exit((void *)(iArg*2)); //和reaturn达到的效果一样,都可以用于正常返回

}

int main()

{

pthread_t thdId;

int iRet = 0;

pthread_create(&thdId, NULL, ThreadFunc, (void *)2 ); //传递参数值为2

pthread_join(thdId,(void **)&iRet); //接收子线程的返回值

printf("The first child thread ret is:%d\n",iRet);

pthread_create(&thdId, NULL, ThreadFunc, (void *)4 );

pthread_join(thdId,(void **)&iRet);

printf("The second child thread ret is:%d\n",iRet);

return 0;

}

2. 该函数还有一个非常重要的作用,由于一个进程中的多个线程共享数据段,因此通常在一个线程退出后,退出线程所占用的资源并不会随线程结束而释放。如果th线程类型并不是自动清理资源类型的,则th线程退出后,线程本身的资源必须通过其它线程调用pthread_join来清除,这相当于多进程程序中的waitpid。

Example:子线程释放空间

#includ

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值