2013-02-25 9 views
8

Jak sprawdzić, czy wątek został zakończony? Próbowałem następujące, ale thread_list nie zawiera wątek, który został uruchomiony, nawet gdy wiem, wątek jest nadal uruchomiony.Python: czy wątek nadal działa

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 

Odpowiedz

17

Kluczem jest, aby rozpocząć wątek przy użyciu wątków, nie wątek:

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

Następnie użyj

z = t1.isAlive() 

lub

l = threading.enumerate() 

Można również użyć join ():

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

To jest mój kod, to nie jest dokładnie to, o co prosiłeś, ale może znajdziesz go użytecznym

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

Twój kod nie wymaga wyjaśnień. musisz odpowiedzieć na pytanie. Jeśli chcesz zasugerować, dodaj to w komentarzach. Ups, potrzebujesz więcej reputacji, aby to zrobić. Do tego czasu spróbuj znaleźć pytanie, na które twoje odpowiedzi są * do rzeczy * i wyjaśniające. – rajuGT

Powiązane problemy