2011-08-23 115 views
0

我想在我的腳本中實現一些基本的線程,我需要檢查線程是否已經存在或沒有,我已經找到了如何設置名稱,但無法弄清楚如何使用is_alive函數名稱按名稱訪問線程

class History(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 

    def run(self): 
     #do some stuff 

for i in range(10): 
    t = History 
    t.setName("name%s"%i)) 
    t().start() 

我以後怎麼檢查是線程name5是否存在?

回答

2

is_alive方法does not take any arguments。您不要按名稱使用is_alive。相反,只需撥打t.is_alive() 即可檢查線程t是否有效。

class History(threading.Thread): 
    def __init__(self,*args,**kwargs): 
     threading.Thread.__init__(self,*args,**kwargs) 

    def run(self): 
     #do some stuff 

threads=[History(name="name%s"%i) for i in range(10)] 
for t in threads: 
    t.start() 

while threads[5].is_alive(): 
    ... 

PS。文檔說name attribute,

...是一個字符串,僅用於識別目的。它有沒有 語義多個線程可能會被賦予相同的名稱

所以不要依賴名稱作爲明確的鑑定手段。

+0

我已更新問題以更具體 – lwolf