Python线程加入死线程

时间:2018-01-08 19:55:03

标签: python python-multithreading

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

e.g。

import threading
import time

def fn():
    time.sleep(1)

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

time.sleep(2)
t.join()

docs似乎没有提供此问题的任何明确性

1 个答案:

答案 0 :(得分:4)

来自您引用的文档:

  

加入:   等到线程终止。 ...

所以如果线程已经终止,当然它会立即退出。

文档中的其他地方:

  

操作将阻塞,直到线程终止。

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

此方法是一种在调用者和线程之间提供同步的方法。在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()