有时候在一个线程中创建了另外一个线程,主线程要等到创建的线程返回了,获取该线程的返回值后才退出,这个时候就需要把线程挂起。
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分配的是堆空间,如何返回个{}中的栈空间的。存疑。