如何知道哪些线程正在运行:Python

6
有没有办法使用Python threading模块知道哪些线程正在运行。使用以下代码,我能够获取线程名称、当前线程和活动线程数。
但是我的疑问在于活动线程是2,而当前线程总是“MainThread”。那么在后台运行的其他线程可能是什么?
import threading
import time

for _ in range(10):
    time.sleep(3)
    print("\n", threading.currentThread().getName())
    print("current thread", threading.current_thread())
    print("active threads ", threading.active_count())

上述代码的输出:

主线程

当前线程 <_MainThread(MainThread, started 11008)>

活动线程数 2


如果上述代码是您的完整程序,则应该只显示一个线程,因为它没有启动任何其他线程。 - Sven Marnach
1个回答

7
您可以使用threading.enumerate()访问所有当前线程对象,例如:
for thread in threading.enumerate():
    print(thread.name)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接