接下來我們看一下線程退出函數和等待函數。
#include <pthread.h>
void pthread_exit(void *value_ptr);
value_ptr:是線程的傳回值。有pthread_join()檢測獲得。
功能:線程退出
#include<pthread.h>
int pthread_join(pthread_t thread, void**value_ptr);
功能:等待指定的線程結束。
傳回值:成功返回0
參數:
thread:等待線程的ID(標示符)
value_ptr:使用者自訂的指標,用來儲存被等待線程的傳回值。
這個函數是線程阻塞函數,調用它的函數將一直阻塞到被等待的線程結束為止,當函數傳回值,被等待線程的資源被回收。
我們看個例子:
#include<stdio.h>
#include<stdlib.h>
void *th_fun1(void*arg)
{
int i=10/2;
printf("%s",arg);
while(i-->0)
fputs("new thread1\n",stdout);
pthread_exit ((void*)1);
}
void *th_fun2(void*arg)
{
int i=10/2;
printf("%s",arg);
while(i-->0)
fputs("new thread 2\n",stdout);
pthread_exit((void*)2);
}
int main()
{
int ret;
pthread_t tid1,tid2;
if((ret=pthread_create(&tid1,NULL,th_fun1,"new thread 1 created!\n"))==-1)
{
perror("pthread_createerror ");
exit(EXIT_FAILURE);
}
if((ret=pthread_create(&tid2,NULL,th_fun2,"new thread 2 created!\n"))==-1)
{
perror("pthread_createerror ");
exit(EXIT_FAILURE);
}
void *fret1;
void *fret2;
pthread_join(tid1,&fret1);
pthread_join(tid2,&fret2);
printf("fret1=%d\n",(int)fret1);
printf("fret2=%d\n",(int)fret2);
return 0;
}