线程挂起

有时候在一个线程中创建了另外一个线程,主线程要等到创建的线程返回了,获取该线程的返回值后才退出,这个时候就需要把线程挂起。

 

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

pthread_join函数用去挂起当前线程,直至th指定的线程终止为止。

/***
hangup.c
***/
#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>

void * func(void *arg)
{
    int i = 0;
    for(; i < 5; i++)
    {
        printf("func run %d\n",i);
        sleep(1);
    }
    int *p = (int *)malloc(sizeof(int));
    *p = 11;
    return p;
}

int main()
{
    pthread_t t1;
    int err = pthread_create(&t1,NULL,func,NULL);
    if( 0 != err)
    {
        printf("thread_create failled : %s\n",strerror(errno));
    }
    else
    {
        printf("thread_create success\n");
    }
    void *p = NULL;
    pthread_join(t1,&p);
    printf("thread exit : code = %d\n",*(int *)p);
    return EXIT_SUCCESS;
}

运行结果:

exbot@ubuntu:~/wangqinghe/thread/20190729$ gcc hangup.c -o hangup -lpthread

exbot@ubuntu:~/wangqinghe/thread/20190729$ ./hangup

thread_create success

func run 0

func run 1

func run 2

func run 3

func run 4

thread exit : code = 11

 

主函数一直带等待创建的线程执行完毕,并得到线程执行结束的返回值。

 

问题:

函数中malloc分配的是堆空间,如何返回个{}中的栈空间的。存疑。

转载于:https://www.cnblogs.com/wanghao-boke/p/11262635.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值