22

如何查看线程是否已完成?我尝试了以下操作,但 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
4

3 回答 3

44

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

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

然后使用

z = t1.is_alive()
# Changed from t1.isAlive() based on comment. I guess it would depend on your version.

或者

l = threading.enumerate()

你也可以使用join():

t1 = threading.Thread(target=my_function, args=())
t1.start()
t1.join()
# Will only get to here once t1 has returned.
于 2013-02-25T10:05:25.713 回答
1

您必须使用 启动线程threading

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

如上所述,如果您没有args要提及的内容,则可以将其留空。

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

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

注意: isAlive()不推荐使用,而是is_alive()按照 python 文档使用。

Python 文档

于 2020-07-21T06:48:29.560 回答
-2

这是我的代码,与您所要求的不完全一样,但也许您会发现它很有用

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**************')
于 2015-09-24T10:14:10.817 回答