Python:线程是否仍在运行

27 投票
3 回答
97519 浏览
提问于 2025-04-17 17:01

我怎么才能知道一个线程是否已经完成呢?我试过以下的方法,但发现 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 个回答

-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**************')
1

你必须通过使用 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 文档

50

关键是要用 threading 来启动线程,而不是用 thread:

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.

撰写回答