如何确定 Python 线程是否已启动?有一个方法
is_alive()
,但这仅在线程运行之前和期间返回 true。使用 isAlive
(或 is_alive
)Thread
类的方法。
Python 2.7 中http://hg.python.org/cpython/file/2.7/Lib/threading.py#l995
def isAlive(self):
"""Return whether the thread is alive.
This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.
"""
assert self.__initialized, "Thread.__init__() not called"
return self.__started.is_set() and not self.__stopped
Python 3 https://github.com/python/cpython/blob/master/Lib/threading.py
Python 3是一种编程语言,具有易读性和清晰度,适用于各种任务。该链接指向线程库的源代码,线程库可用于在Python程序中实现并发。def is_alive(self):
"""Return whether the thread is alive.
This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.
"""
assert self._initialized, "Thread.__init__() not called"
if self._is_stopped or not self._started.is_set():
return False
self._wait_for_tstate_lock(False)
return not self._is_stopped
Thread.start
并设置一个标志。 - Razer
__started
已设置,但线程尚未运行(我认为这是非常短暂的时间)。 - ndpu