Joh*_*nnB 5 python python-multithreading
join()如果我调用一个已经完成的线程会发生什么?
例如
import threading
import time
def fn():
time.sleep(1)
t = threading.Thread(target=fn)
t.start()
time.sleep(2)
t.join()
Run Code Online (Sandbox Code Playgroud)
该文档似乎没有对这个问题提供任何说明
从您引用的文档中:
join:等待线程终止。...
因此,如果线程已经终止,当然它会立即退出。
文档的其他地方也有:
该操作将阻塞,直到线程终止。
好的,如果它已经终止,则操作不会阻塞。
该方法是一种在调用者和线程之间提供同步的方法。退出后join,保证线程结束。如果调用时线程已经结束join,那么它当然不会执行任何操作。
python 源代码证实了这一点(该函数是从以下位置调用的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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2853 次 |
| 最近记录: |