线程等待
函数定义
#include <pthread.h>
int pthread_join(pthread_t tid, void **rval_ptr);
阻塞调用线程,直到指定的线程终止。
返回值
成功返回0,失败返回错误码。
错误码定义如下:
ERRORS
EDEADLK
A deadlock was detected (e.g., two threads tried to join with each other); or thread specifies the calling thread.(检测到死锁)
EINVAL thread is not a joinable thread.(不是可连接的线程)
EINVAL Another thread is already waiting to join with this thread.(另一个线程已经在等待加入这个线程)
ESRCH No thread with the ID thread could be found.(找不到对应ID的线程)
参数
tid:等待退出的线程id
rval_ptr:线程退出的返回值指针
示例
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
void *myThread(void *str)
{
for(int i = 0; i < 5; i++)
{
sleep(2);
printf("child thread is : %d\n", i);
}
return NULL;
}
int main()
{
pthread_t tid;
int ret, i;
ret = pthread_create(&tid, NULL, myThread, NULL);
if(ret != 0)
{
printf("thread create error!\n");
return -1;
}
ret = pthread_join(tid, NULL);
if(ret != 0)
{
printf("thread join error!\n");
return -2;
}
for(i = 0; i < 5; i++)
{
sleep(1);
printf("main thread is : %d\n", i);
}
return 0;
}
编译运行:
[root@192 pthread]# gcc -lpthread pthread_join.c -o pthread_join
[root@192 pthread]# ./pthread_join
child thread is : 0
child thread is : 1
child thread is : 2
child thread is : 3
child thread is : 4
main thread is : 0
main thread is : 1
main thread is : 2
main thread is : 3
main thread is : 4