Python:从“threading.local”中获取所有项目

2024-02-15

我有一个threading.local目的。调试时,我想获取所有线程包含的所有对象,而我只在其中一个线程上。我怎样才能做到这一点?


如果您使用的是纯Python版本threading.local (from _threading_local import local), 这个有可能:

for t in threading.enumerate():
    for item in t.__dict__:
       if isinstance(item, tuple):  # Each thread's `local` state is kept in a tuple stored in its __dict__
           print("Thread's local is %s" % t.__dict__[item])

这是一个实际的例子:

from _threading_local import local
import threading
import time

l = local()

def f():
   global l
   l.ok = "HMM"
   time.sleep(50)

if __name__ == "__main__":
    l.ok = 'hi'
    t = threading.Thread(target=f)
    t.start()
    for t in threading.enumerate():
        for item in t.__dict__:
           if isinstance(item, tuple):
               print("Thread's local is %s" % t.__dict__[item])

Output:

Thread's local is {'ok': 'hi'}
Thread's local is {'ok': 'HMM'}

这是利用了以下事实:纯 python 实现local存储每个线程的local状态在Thread对象的__dict__,使用元组对象作为键:

>>> threading.current_thread().__dict__
{ ..., ('_local__key', 'thread.local.140466266257288'): {'ok': 'hi'}, ...}

如果您正在使用的实现local写在C(如果您只使用,通常会出现这种情况from threading import local),我不确定你如何/是否可以做到。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:从“threading.local”中获取所有项目 的相关文章

随机推荐