pthread_join使一个线程等待另一个线程结束。
我们知道,如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。
1.pthread_join
#include <pthread.h>
int pthread_join(pthread_t thread, void **value_ptr);
参数: - thread:等待退出线程的线程号。 - value_ptr:退出线程的返回值。
返回值: - 成功返回0,失败返回非0。
实例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thr_fn(void *arg)
{
printf("son thread is running...\n");
sleep(3);
printf("************son thread will exit************\n");
}
int main(int argc, char const *argv[])
{
printf("main thread is running....\n");
pthread_t thread;
//线程传参
if (pthread_create(&thread, NULL, thr_fn, NULL) != 0)
{
perror("error to pthread_create:");
exit(-1);
}
//等待子线程的结束
if (pthread_join(thread, NULL) != 0)
{
perror("error to join:");
exit(-1);
}
printf("main thread will exit....\n");
return 0;
}
执行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
main thread is running....
son thread is running...
************son thread will exit************
main thread will exit....
获取子线程的返回值:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void *thr_fn(void *arg)
{
//尽量不要使用栈区的变量,比如int status=666;
static int status=666;
printf("son thread is running...\n");
sleep(3);
printf("************son thread will exit************\n");
return (void *)&status;
}
int main(int argc, char const *argv[])
{
printf("main thread is running....\n");
pthread_t thread;
//线程传参
if (pthread_create(&thread, NULL, thr_fn, NULL) != 0)
{
perror("error to pthread_create:");
exit(-1);
}
int *status;
//等待子线程的结束
if (pthread_join(thread, (void **)&status) != 0)
{
perror("error to join:");
exit(-1);
}
printf("return status=%d\n",*status);
printf("main thread will exit....\n");
return 0;
}
运行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
main thread is running....
son thread is running...
************son thread will exit************
return status=666
main thread will exit....