Python:线程仍在运行

时间:2013-02-25 09:39:06

标签: python multithreading

如何查看线程是否已完成?我尝试了以下内容,但threads_list不包含已启动的线程,即使我知道该线程仍在运行。

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

3 个答案:

答案 0 :(得分:23)

关键是使用线程启动线程,而不是线程:

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

然后使用

z = t1.isAlive()

l = threading.enumerate()

您也可以使用join():

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

答案 1 :(得分: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**************')

答案 2 :(得分:0)

您必须使用threading启动线程。

id1 = threading.Thread(target = my_function)
id1.start()

从上面开始,如果您没有args要提及,则可以将其留空。

要检查线程是否存在,可以使用is_alive()

if id1.is_alive():
   print("Is Alive")
else:
   print("Dead")

注意::不推荐使用isAlive(),而根据python文档使用is_alive()

Python Documentation