Skip to main content
 首页 » 编程设计

python之threading.enumerate() 中是否有特定线程

2024年11月01日40shihaiming

我需要检查特定线程是否在 threading.enumerate() 的结果中。

假设我通过枚举得到了结果:

<_MainThread(MainThread, started 8568)> 
<Thread(Thread-263, started 11116)> 
<MyThread(Thread-235, started 21045)> 

如何检查线程 MyThread 是否在我的结果中?

请您参考如下方法:

过滤线程类:

>>> import threading 
>>> class MyThread(threading.Thread): pass 
... 
>>> def do_nothing(): 
...     while True: 
...         pass 
 
>>> MyThread(target=do_nothing).start() 
>>> threading.Thread(target=do_nothing).start() 
>>> threading.enumerate() 
[<MyThread(Thread-1, started 8040)>, <Thread(Thread-2, started 7352)>, <_MainThread(MainThread, started 2772)>] 
>>> [t for t in threading.enumerate() if isinstance(t, MyThread)] 
[<MyThread(Thread-1, started 8040)>]