使用 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() 返回之后,应用程序可回收与已终止线程关联的任何数据存储空间。