不同模块中的python threading.local()

不同模块中的python threading.local(),python,multithreading,module,local,Python,Multithreading,Module,Local,我试图将threading.local()中的数据传递给不同模块中的函数。 代码是这样的: 其他_module.py: import threading # 2.1 ll = threading.local() def other_fn(): # 2.2 ll = threading.local() v = getattr(ll, "v", None) print(v) import threading import other_module # 1.1 ll =

我试图将threading.local()中的数据传递给不同模块中的函数。 代码是这样的:

其他_module.py:

import threading

# 2.1  
ll = threading.local()

def other_fn():

 # 2.2    
 ll = threading.local()

 v = getattr(ll, "v", None)
 print(v)
import threading
import other_module

# 1.1
ll = threading.local()

def main_fn(v):

 # 1.2
 ll = threading.local()

 ll.v = v
 other_fn()


for i in [1,2]:
 t = threading.Thread(target=main_fn, args=(i,))
 t.start()
main_module.py:

import threading

# 2.1  
ll = threading.local()

def other_fn():

 # 2.2    
 ll = threading.local()

 v = getattr(ll, "v", None)
 print(v)
import threading
import other_module

# 1.1
ll = threading.local()

def main_fn(v):

 # 1.2
 ll = threading.local()

 ll.v = v
 other_fn()


for i in [1,2]:
 t = threading.Thread(target=main_fn, args=(i,))
 t.start()
但是1.x-2.x组合中没有一个不适合我。 我发现了类似的问题-但如果打印消息功能位于不同的模块中,则标记为“回答”的回答对我也不起作用


是否可以在模块之间传递线程本地数据而不将其作为函数参数传递?

在类似的情况下,我在一个单独的模块中完成了以下操作:

import threading
from collections import defaultdict

tls = defaultdict(dict)


def get_thread_ctx():
    """ Get thread-local, global context"""
    return tls[threading.get_ident()]
这实际上创建了一个名为tls的
全局
变量。然后,每个线程(基于其标识)在全局dict中获得一个键。我也将其作为dict处理。例如:

class Test(Thread):
    def __init__(self):
        super().__init__()
        # note: we cannot initialize thread local here, since thread 
        # is not running yet

    def run(self):
        # Get thread context
        tmp = get_thread_ctx()
        # Create an app-specific entry
        tmp["probe"] = {}
        self.ctx = tmp["probe"]

        while True:
            ...
现在,在另一个模块中:

def get_thread_settings():
    ctx = get_thread_ctx()
    probe_ctx = ctx.get("probe", None)

    # Get what you need from the app-specific region of this thread
    return probe_ctx.get("settings", {})

希望它能帮助下一个寻找类似事物的人

你找到答案了吗?可能是@ShivanshJagga的重复不,我没有。我希望它使用OS原生TLS,但事实并非如此。因此,我最终将所有需要的数据作为线程函数参数传递。