python线程.local()在不同的modu中

2024-04-26 11:59:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着把数据传进来线程.local()到不同模块中的函数。 代码是这样的:

其他_模块.py公司名称:

import threading

# 2.1  
ll = threading.local()

def other_fn():

 # 2.2    
 ll = threading.local()

 v = getattr(ll, "v", None)
 print(v)

主_模块.py公司名称:

^{pr2}$

但是1.x-2.x的组合都不适合我。 我发现了类似的问题-Access thread local object in different module - Python但是回复,如果打印消息函数位于不同的模块中,则标记为答案对我也不起作用。在

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


Tags: 模块数据函数代码pyimport名称local
1条回答
网友
1楼 · 发布于 2024-04-26 11:59:50

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

import threading
from collections import defaultdict

tls = defaultdict(dict)


def get_thread_ctx():
    """ Get thread-local, global context"""
    return tls[threading.get_ident()]

这实际上创建了一个名为tls的global变量。然后每个线程(基于其标识)在全局dict.I句柄中获取一个密钥,该密钥也作为dict处理。示例:

^{pr2}$

现在,在另一个模块中:

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", {})

希望它能帮助下一个寻找类似的东西

相关问题 更多 >