gpt4 book ai didi

Python 线程加入死线程

转载 作者:行者123 更新时间:2023-11-28 22:21:40 26 4
gpt4 key购买 nike

如果我在一个已经完成的线程上调用 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()

关于Python 线程加入死线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48157208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com