Python 线程加入死线程

Python Threading Joining a Dead Thread

如果我在已经完成的线程上调用 join() 会怎样?

例如

import threading
import time

def fn():
    time.sleep(1)

t = threading.Thread(target=fn)
t.start()

time.sleep(2)
t.join()

docs 似乎没有就此问题提供任何说明

来自您引用的文档:

join: Wait until the thread terminates. ...

所以如果线程已经终止了,当然是马上退出了。

文档的其他地方:

the operation will block until the thread terminates.

好的,如果它已经终止,操作不会阻塞。

此方法是一种在调用者和线程之间提供同步的方法。 join 退出后,保证线程结束。如果在调用 join 时线程已经结束,那么它当然什么都不做。

这由 python source code 确认(此函数从 join() 调用:

def _wait_for_tstate_lock(self, block=True, timeout=-1):
    # Issue #18808: wait for the thread state to be gone.
    # At the end of the thread's life, after all knowledge of the thread
    # is removed from C data structures, C code releases our _tstate_lock.
    # This method passes its arguments to _tstate_lock.acquire().
    # If the lock is acquired, the C code is done, and self._stop() is
    # called.  That sets ._is_stopped to True, and ._tstate_lock to None.
    lock = self._tstate_lock
    if lock is None:  # already determined that the C code is done
        assert self._is_stopped   # we see that we don't wait for anything here
    elif lock.acquire(block, timeout):
        lock.release()
        self._stop()