c主线程如何等待子线程结束 linux_pthread_join pthread_exit 线程 Linux函数 线程退出 线程等待 | 学步园...

接下来我们看一下线程退出函数和等待函数。

#include

void pthread_exit(void *value_ptr);

value_ptr:是线程的返回值。有pthread_join()检测获得。

功能:线程退出

#include

int pthread_join(pthread_t thread, void**value_ptr);

功能:等待指定的线程结束。

返回值:成功返回0

参数:

thread:等待线程的ID(标示符)

value_ptr:用户自定义的指针,用来保存被等待线程的返回值。

这个函数是线程阻塞函数,调用它的函数将一直阻塞到被等待的线程结束为止,当函数返回值,被等待线程的资源被回收。

我们看个例子:

#include

#include

void *th_fun1(void*arg)

{

int i=10/2;

printf("%s",arg);

while(i-->0)

fputs("new thread1\n",stdout);

pthread_exit ((void*)1);

}

void *th_fun2(void*arg)

{

int i=10/2;

printf("%s",arg);

while(i-->0)

fputs("new thread 2\n",stdout);

pthread_exit((void*)2);

}

int main()

{

int ret;

pthread_t tid1,tid2;

if((ret=pthread_create(&tid1,NULL,th_fun1,"new thread 1  created!\n"))==-1)

{

perror("pthread_createerror ");

exit(EXIT_FAILURE);

}

if((ret=pthread_create(&tid2,NULL,th_fun2,"new thread 2  created!\n"))==-1)

{

perror("pthread_createerror ");

exit(EXIT_FAILURE);

}

void *fret1;

void *fret2;

pthread_join(tid1,&fret1);

pthread_join(tid2,&fret2);

printf("fret1=%d\n",(int)fret1);

printf("fret2=%d\n",(int)fret2);

return 0;

}

1336200851_9350.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值