Ram*_*hum 7 python multithreading
我有一个threading.local对象.在调试时,我想获得它为所有线程包含的所有对象,而我只是在其中一个线程上.我怎样才能做到这一点?
threading.local如果您使用( )的纯 python 版本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])
Run Code Online (Sandbox Code Playgroud)
这是一个实际的例子:
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])
Run Code Online (Sandbox Code Playgroud)
输出:
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])
Run Code Online (Sandbox Code Playgroud)
这是利用以下事实: 的纯 python 实现local将每个线程的local状态存储在Thread对象的中__dict__,并使用元组对象作为键:
>>> threading.current_thread().__dict__
{ ..., ('_local__key', 'thread.local.140466266257288'): {'ok': 'hi'}, ...}
Run Code Online (Sandbox Code Playgroud)
local如果您使用的是write in的实现C(如果您只使用,则通常是这种情况from threading import local),我不确定您如何/是否可以做到这一点。