pthread_join() 函数会一直阻塞调用线程,直到指定的线程终止。
使用 pthread_join(3C) 等待线程终止。
int pthread_join(thread_t tid, void **status);
#include <pthread.h> pthread_t tid; int ret; void *status; /* waiting to join thread "tid" with status */ ret = pthread_join(tid, &status); /* waiting to join thread "tid" without status */ ret = pthread_join(tid, NULL);
指定的线程必须位于当前的进程中,而且不得是分离线程。有关线程分离的信息,请参见设置分离状态。
当 status 不是 NULL 时,status 指向某个位置,在 pthread_join() 成功返回时,将该位置设置为已终止线程的退出状态。
如果多个线程等待同一个线程终止,则所有等待线程将一直等到目标线程终止。然后,一个等待线程成功返回。其余的等待线程将失败并返回 ESRCH 错误。
在 pthread_join() 返回之后,应用程序可回收与已终止线程关联的任何数据存储空间。
调用成功完成后,pthread_join() 将返回零。其他任何返回值都表示出现了错误。如果检测到以下任一情况,pthread_join() 将失败并返回相应的值。
ESRCH
描述:没有找到与给定的线程 ID 相对应的线程。
EDEADLK
描述:将出现死锁,如一个线程等待其本身,或者线程 A 和线程 B 互相等待。
EINVAL
描述:与给定的线程 ID 相对应的线程是分离线程。
pthread_join() 仅适用于非分离的目标线程。如果没有必要等待特定线程终止之后才进行其他处理,则应当将该线程分离。