Her*_*arn 6 python multithreading
有什么方法可以知道使用 python 线程模块正在运行哪些线程。使用以下代码,我可以获得线程名称、当前线程、活动线程数。
但我的疑问是 ACTIVE_THREADS 为 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())
Run Code Online (Sandbox Code Playgroud)
主线程
当前线程 <_MainThread(MainThread, started 11008)>
活动线程 2
您可以使用threading.enumerate(),例如访问所有当前线程对象
for thread in threading.enumerate():
print(thread.name)
Run Code Online (Sandbox Code Playgroud)