如果您使用的是纯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
),我不确定你如何/是否可以做到。