gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:07:50 25 4
gpt4 key购买 nike

我正在尝试将 threading.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:
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 对我不起作用。
我发现了类似的问题 - Access thread local object in different module - Python 但如果 print_message 函数位于 不同的模块 中,则回复,标记为答案对我也不起作用。

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

最佳答案

在类似的情况下,我最终在一个单独的模块中执行了以下操作:

import threading
from collections import defaultdict

tls = defaultdict(dict)


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

这实质上创建了一个 global名为 tls 的变量。然后每个线程(基于其身份)在全局字典中获得一个键。我也把它当作一个字典来处理。例子:
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", {})

希望它可以帮助下一个寻找类似东西的人

关于python threading.local() 在不同的模块中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53764674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com