代码之家  ›  专栏  ›  技术社区  ›  JohannB

Python线程连接死线程

  •  2
  • JohannB  · 技术社区  · 7 年前

    如果我打电话怎么办 join() 在已经完成的线程上?

    例如

    import threading
    import time
    
    def fn():
        time.sleep(1)
    
    t = threading.Thread(target=fn)
    t.start()
    
    time.sleep(2)
    t.join()
    

    这个 docs 似乎没有提供任何关于这个问题的明确信息

    1 回复  |  直到 7 年前
        1
  •  4
  •   Jean-François Fabre    7 年前

    从您引用的文档中:

    加入: 等待线程终止。。。

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

    文件中的其他地方:

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

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

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