2013-02-25 104 views
8

如何查看線程是否已完成?我嘗試了以下,但threads_list不包含已啓動的線程,即使我知道線程仍在運行。Python:線程仍在運行

import thread 
import threading 

id1 = thread.start_new_thread(my_function,()) 
#wait some time 
threads_list = threading.enumerate() 
# Want to know if my_function() that was called by thread id1 has returned 

def my_function() 
    #do stuff 
    return 

回答

17

的關鍵是使用線程啓動線程,不是線程:

t1 = threading.Thread(target=my_function, args=()) 
t1.start() 

然後使用

z = t1.isAlive() 

l = threading.enumerate() 

你也可以使用加入( ):

t1 = threading.Thread(target=my_function, args=()) 
t1.start() 
t1.join() 
# Will only get to here once t1 has returned. 
0

這是我的代碼,這不完全是你問什麼,但也許你會發現它有用

import time 
import logging 
import threading 

def isTreadAlive(): 
    for t in threads: 
    if t.isAlive(): 
     return 1 
    return 0 


# main loop for all object in Array 

threads = [] 

logging.info('**************START**************') 

for object in Array: 
    t= threading.Thread(target=my_function,args=(object,)) 
    threads.append(t) 
    t.start() 

flag =1 
while (flag): 
    time.sleep(0.5) 
    flag = isTreadAlive() 

logging.info('**************END**************') 
+1

代碼未解釋的。你必須回答這個問題。如果您想提出建議,只需在評論中添加即可。哎呀,你需要更多的聲譽來做到這一點。直到那時,試着找到你認爲你的答案是*的問題*和解釋性的問題。 – rajuGT 2015-09-24 10:43:18