1.1. 等待线程退出
线程从入口点函数自然返回,或者主动调用pthread_exit()函数,都可以让线程正常终止
线程从入口点函数自然返回时,函数返回值可以被其它线程用pthread_join函数获取
pthread_join原型为:
#include
int pthread_join(pthread_t th, void **thread_return);
1. 该函数是一个阻塞函数,一直等到参数th指定的线程返回;与多进程中的wait或waitpid类似。
thread_return是一个传出参数,接收线程函数的返回值。如果线程通过调用pthread_exit()终止,则pthread_exit()中的参数相当于自然返回值,照样可以被其它线程用pthread_join获取到。
Example:返回值的例子
#include
#include
#include
void *ThreadFunc(void *pArg)
{
int iArg = (int)pArg; //将void*转换为int
sleep(iArg);
if(iArg < 3)
return (void *)(iArg*2);
else
pthread_exit((void *)(iArg*2)); //和reaturn达到的效果一样,都可以用于正常返回
}
int main()
{
pthread_t thdId;
int iRet = 0;
pthread_create(&thdId, NULL, ThreadFunc, (void *)2 ); //传递参数值为2
pthread_join(thdId,(void **)&iRet); //接收子线程的返回值
printf("The first child thread ret is:%d\n",iRet);
pthread_create(&thdId, NULL, ThreadFunc, (void *)4 );
pthread_join(thdId,(void **)&iRet);
printf("The second child thread ret is:%d\n",iRet);
return 0;
}
2. 该函数还有一个非常重要的作用,由于一个进程中的多个线程共享数据段,因此通常在一个线程退出后,退出线程所占用的资源并不会随线程结束而释放。如果th线程类型并不是自动清理资源类型的,则th线程退出后,线程本身的资源必须通过其它线程调用pthread_join来清除,这相当于多进程程序中的waitpid。
Example:子线程释放空间
#includ