python threading.local() 在不同的模块中
python threading.local() in different module
我正在尝试将 threading.local() 中的数据传递给 不同模块 中的函数。
代码是这样的:
other_module.py:
import threading
# 2.1
ll = threading.local()
def other_fn():
# 2.2
ll = threading.local()
v = getattr(ll, "v", None)
print(v)
main_module.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()
但是 none 组合 1.x - 2.x 对我不起作用。
我发现了类似的问题 - 但回复,如果 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()]
这实际上创建了一个名为 tls 的 global
变量。然后每个线程(基于其身份)在全局字典中获得一个键。我也将其作为命令处理。示例:
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", {})
希望它能帮助下一个寻找类似东西的人
我正在尝试将 threading.local() 中的数据传递给 不同模块 中的函数。 代码是这样的:
other_module.py:
import threading
# 2.1
ll = threading.local()
def other_fn():
# 2.2
ll = threading.local()
v = getattr(ll, "v", None)
print(v)
main_module.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()
但是 none 组合 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 的 global
变量。然后每个线程(基于其身份)在全局字典中获得一个键。我也将其作为命令处理。示例:
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", {})
希望它能帮助下一个寻找类似东西的人