2014-02-22 61 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 

# ... 
相關問題