pthread_join() 是一个关键函数吗?

Is pthread_join() a critical function?

根据POSIX,如果原始承载线程完成,则可以重新使用线程 ID。因此,在调用 pthread_join() 时是否需要使用互斥量或信号量?因为,在原始线程中调用 pthread_join() 之前,可能会发生想要加入的目标线程已经终止并创建了具有相同线程 ID 的另一个线程。这将使原始线程相信目标线程尚未完成,尽管事实并非如此。

我想您会发现它的工作方式与 UNIX 中的进程非常相似。一个可连接的线程不会被视为真正完成,直到有东西真正加入它。

这与 UNIX 进程的相似之处在于,即使它们在技术上已经退出,但在另一个进程执行 wait 在上面。只有在那之后,PID 才可以重新使用。这种进程称为僵尸进程,死而不死

这得到 pthread_join documentation 的支持,其中指出:

Failure to join with a thread that is joinable (i.e., one that is not detached), produces a "zombie thread". Avoid doing this, since each zombie thread consumes some system resources, and when enough zombie threads have accumulated, it will no longer be possible to create new threads (or processes).

pthread_create,其中指出:

Only when a terminated joinable thread has been joined are the last of its resources released back to the system.