[英]Python: is thread 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
关键是使用线程启动线程,而不是线程:
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.
您必须使用threading
来启动threading
。
id1 = threading.Thread(target = my_function)
id1.start()
如上所述,如果您没有任何args
可提及,您可以将其留空。
要检查您的线程是否is_alive()
活动状态,您可以使用is_alive()
if id1.is_alive():
print("Is Alive")
else:
print("Dead")
注意:不推荐使用isAlive()
而是根据 python 文档使用is_alive()
。
这是我的代码,这不是你问的,但也许你会发现它很有用
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**************')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.