确定线程是否已经启动

5
如何确定 Python 线程是否已启动?有一个方法 is_alive(),但这仅在线程运行之前期间返回 true。

应该在启动之前返回false。文档字符串中的“方法开始之前”意味着__started已设置,但线程尚未运行(我认为这是非常短暂的时间)。 - ndpu
3个回答

9
您可以查看实例的ident字段。Python 2.7 Threading文档ident描述为线程的“线程标识符”,如果线程尚未启动,则为None。

3

使用 isAlive(或 is_aliveThread 类的方法。

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

1
你可以让线程函数在启动时设置一个布尔标志,然后检查该标志。

这不完全是我要找的。线程启动和执行之间总会有延迟。我想避免这种问题。一种可能性是重载 Thread.start 并设置一个标志。 - Razer
2
@Razer 你通常无法避免线程启动和实际执行之间的延迟,任何依赖这种情况的设计都是有缺陷的。无论如何,你真的不应该需要这样的标志 - 你实际要解决的问题是什么? - Voo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接