Python:线程是否仍在运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15063963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:13:37  来源:igfitidea点击:

Python: is thread still running

pythonmultithreading

提问by user984003

How do I see whether a thread has completed? I tried the following, but threads_list does not contain the thread that was started, even when I know the thread is still running.

如何查看线程是否已完成?我尝试了以下操作,但即使我知道线程仍在运行,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

采纳答案by user984003

The key is to start the thread using threading, not thread:

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

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

Then use

然后使用

z = t1.isAlive()

or

或者

l = threading.enumerate()

You can also use join():

您还可以使用 join():

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

回答by Noam Rones

This is my code, It's not exactly what you asked, but maybe you will find it useful

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

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