线程等待:
等待一个指定线程的退出,获取这个退出线程的返回值,并且允许系统回收这个线程占用的资源。
但是,并不是所有的线程都需要被等待,因此线程有一个属性,默认为joinable。处于这个属性的线程,退出后不会自动回收资源。需要其他线程进行等待处理。
如何等待:
int pthread_join(pthread_t tid, void **retval);
tid:用于指定要等待的线程
retval:输出性参数,返回线程的退出返回值
retval为什么是一个二级指针:
int a=10; test(int *b){*b=1;} test(&a)
a=? (10)
线程的返回值是一个一级指针,(b就是一个一级指针)因此对一级指针取地址应该用二级指针。
int *a{这个变量拥有一块空间,可以存放另一款空间的地址}
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *thr_start(void *arg)
{
pthread_detach(pthread_self());//分离自己
printf("Normal thread will exit in 3 seconds\n");
sleep(3);
char *buf = "nihao\n"; //返回的是常量的地址
//char buf[] = "nihao\n"; //返回的是局部空间的地址
return buf;
}
int main()
{
pthread_t tid;
int ret = pthread_create(&tid, NULL, thr_start, NULL);
if (ret != 0) {
printf("thread create failed!!\n");
return -1;
}
printf("Main thread waiting for normal thread to exit\n");
char *retval = NULL;
//pthread_join(tid, (void**)&retval);//等待一个线程的退出,若线程没有退出,则会一直等待
//pthread_detach(tid);
while(1) {
printf("retval:%s\n", retval);
sleep(1);
}