本文介绍了Python:从`threading.local`中取出所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个threading.local对象.调试时,我只想获取所有线程包含的所有对象,而我仅位于这些线程之一上.我怎样才能做到这一点?

I have a threading.local object. When debugging, I want to get all the objects it contains for all threads, while I am only on one of those threads. How can I do that?

推荐答案

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

If you're using the pure-python version of threading.local (from _threading_local import local), this is possible:

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])

输出:

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

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

This is exploiting the fact that the pure-python implementation of local stores each thread's local state in the Thread object's __dict__, using a tuple object as the key:

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

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

If you're using the implementation of local written in C (which is usually the case if you just use from threading import local), I'm not sure how/if you can do it.

这篇关于Python:从`threading.local`中取出所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 17:45