【问题标题】:Python: is thread still runningPython:线程还在​​运行吗
【发布时间】:2013-02-25 09:39:06
【问题描述】:

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

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

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

    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.
    

    【讨论】:

    • 2019 答案:使用is_alive 而不是isAlive;您将看到上述答案的弃用警告。
    • @Tommy 这就是我的答案,我认为这在这种情况下很重要,所以我发布了它。
    • 只是一个建议:请记住,如果您还没有调用startis_alive 也会返回 True。如果你的程序很复杂,并且有任何条件启动你的威胁,你可以将程序置于死锁状态。
    【解决方案2】:

    您必须使用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

    【讨论】:

      【解决方案3】:

      这是我的代码,不是你问的,但也许你会发现它很有用

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

      【讨论】:

      • 您的代码没有解释性。你必须回答这个问题。如果您想建议,只需将其添加到 cmets 中即可。哎呀,你需要更多的声誉才能做到这一点。在此之前,请尝试找出您认为自己的答案中肯且具有解释性的问题。
      • for 循环不正确。如果线程之一是Alive,则返回1。
      猜你喜欢
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多