[英]python threading.local() in different module
我試圖將 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)
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()
但是沒有一個組合 1.x - 2.x 不適合我。 我發現了類似的問題 - 訪問不同模塊中的線程本地對象 - 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()]
這實質上創建了一個名為 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", {})
希望它可以幫助下一個尋找類似的東西
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.