2014-02-22 62 views
1

如何确定python线程是否已启动?有一种方法is_alive()但同时一个线程在运行,这是真正的之前。确定线程是否已启动

+0

'回归自我.__ started.is_set(),而不是自我.__ stopped'应返回false开始前。 '在方法开始之前'从doc str意味着'__started'被设置,但线程还没有运行(很短的时间,我想) – ndpu

回答

0

你可以有线程函数设置一个布尔标志上启动,然后检查标志。

+0

这并不是我正在寻找的。线程开始和执行时间之间总会有一段延迟。我想避免之间的这个小故障。一种可能性是重载'Thread.start'并设置一个标志。 – Razer

+2

@Razer通常情况下,你不能避免线程被启动和实际执行之间的延迟,任何依赖这样的东西的设计都被定义为破坏。总之,你真的不应该需要这样的标志 - 你试图解决什么样的问题? – Voo

1

使用isAlive(或is_aliveThread类方法。

从源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 

# ... 
相关问题