如何查看线程是否已完成?我尝试了以下操作,但 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.
关于Python:线程是否仍在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15063963/