根据 POSIX,如果原始承载线程完成,则可以重用线程 ID。因此,在调用 pthread_join()
时是否需要使用互斥量或信号量?因为,在原始线程中调用 pthread_join()
之前,可能会发生想要加入的目标线程已经终止并创建了具有相同线程 ID 的另一个线程。这将使原始线程相信目标线程尚未完成,尽管事实并非如此。
最佳答案
我想您会发现它的工作方式与 UNIX 中的进程非常相似。在某些东西实际加入之前,可连接线程不会被视为真正完成。
这与 UNIX 进程的相似之处在于,即使它们在技术上已经退出,但仍有足够的状态信息(包括 PID,目前还不能重新使用),直到另一个进程执行 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.
关于linux - pthread_join() 是一个关键函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43087721/