Python:线程是否仍在运行

标签 python multithreading

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

相关文章:

python - 如何让 minimax 算法返回实际移动?

c++ - 如何封装一个线程?

python - python函数如何调用并且不等待它完成处理,而该函数必须被调用一次。因此,线程必须停止

c++ - 在 C++ 中的两个不同核心中创建两个线程

python - SQLAlchemy - 有没有办法查看当前 session 中的内容?

python - 使用 'value' 作为主键和 'key' 作为辅助键对 python 字典进行排序

python - 如何使 C++ 将二维数组返回给 Python

python - PostgreSQL 物化 View 未从 Python 刷新

c++0x 线程初始化

C# 线程 - 如何启动和停止线程