【问题标题】:python threading.local() in different modulepython threading.local() 在不同的模块中
【发布时间】:2018-12-13 15:02:15
【问题描述】:

我正在尝试将 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()

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

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

【问题讨论】:

  • 你找到答案了吗?
  • @ShivanshJagga 不,我没有。我希望它使用操作系统本机 TLS,但事实并非如此。所以我最终将我需要的所有数据作为线程函数参数传递。

标签: python multithreading module local


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2015-04-04
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 2015-10-26
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多