网络编程(35)—— 利用pthread_join函数等待线程结束并获取线程函数返回值

        在linux中的多线程一节中,我们介绍了利用pthread_create()函数创建子线程的方法。这种方式创建的线程存在一个问题:在主线程创建完成子线程后,若子线程函数
还没结束时,但是此时主线程函数已经结束,那么子线程也会被强制销毁,为了避免这个问题,当时我们在主线程中sleep了11秒钟以等待子线程的结束。虽然暂时避免了问题的发生,但是显然这不是很友好的解决方案,因为在实际编程中你无法预料子线程什么时候会结束,也就无法给出准确的sleep的时间。
        本文主要讨论下利用pthread_join()函数解决这个问题,首先,看一下函数的原型:
#include 
int pthread_join(pthread_t thread, void **retval);

        pthread_join的第一个参数是创建的子线程线程ID,第二个参数是子线程函数的返回值地址的指针,也就是其返回值地址的地址。pthread_join的作用就是等待第一个参数指定的线程的结束,在等待期间该函数是阻塞的,等到子线程结束后,函数结束阻塞状态。下面我们就在代码中演示下pthread_join的用法:

#include
#include

void* thread_main(void* pmax)
{
int i;
int max=*((int*)pmax);
for(i=0;i

第4行我们定义了一个线程的主函数thread_main;
第21行利用pthread_create()函数创建了一个线程,分别将通过pid获取到了线程ID、传入线程函数,然后利用max传入线程函数的参数。
第22行调用pthread_join()函数等待线程的结束,通过函数的第一个参数指定要等待的线程,第二个参数用来接收线程函数返回值,注意rst是一个void**的指针。
最后打印出线程函数的返回值。
        至此,我们没有使用sleep()函数使主线程睡,也完美实现了等待子线程的结束,来看下运行结果:
[Hyman@Hyman-PC multithread]$ gcc ts.c -lpthread
[Hyman@Hyman-PC multithread]$ ./a.out 
child thread called...
child thread called...
child thread called...
child thread called...
child thread called...
child thread called...
child thread called...
child thread called...
child thread called...
child thread called...
the child return: Tread ended ...


Github位置:
https://github.com/HymanLiuTS/NetDevelopment
克隆本项目:
git clone [email protected]:HymanLiuTS/NetDevelopment.git
获取本文源代码:
git checkout NL35

你可能感兴趣的:(网络通信编程,网络通信编程)