全局定义的线程本地属性在线程中不可访问

2024-06-16 10:26:43 发布

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

import threading


threadlocal = threading.local()
threadlocal.depth = 0


def _increase_depth():
    threadlocal.depth += 1


def _decrease_depth():
    threadlocal.depth -= 1


def _use_it():
    print(threadlocal.depth)

但我得到:

AttributeError: '_thread._local' object has no attribute 'depth'

我所期望的是:每个线程得到一个初始化为depth0,修改只在该特定线程中可见

为什么threadlocal中定义的属性在线程中不可访问

(这段代码是在django测试服务器的开发中运行的:我还没有调整它以生成一个可以用普通线程演示的最小示例)


Tags: importobjectuselocaldefit线程thread
2条回答

此实现解决了我的问题:

import threading

_INDENT = '   '

_threadlocal = threading.local()
_defaults = dict(depth=0, prefix='')


class ThreadLocal:

    _initialized = False  # This allows us to set / get attributes during __init__

    def __init__(self, thread_data, defaults=None):
        self._thread_data = thread_data
        self._defaults = defaults or {}
        self._initialized = True

    def __setattr__(self, key, value):
        if self._initialized:
            setattr(self._thread_data, key, value)
        else:
            # Allow setting attributes in __init__
            self.__dict__[key] = value

    def __getattr__(self, item):
        if self._initialized:
            return getattr(self._thread_data, item, _defaults.get(item))
        else:
            # Allow getting attributes in __init__
            return self.__dict__[item]


threadlocal = ThreadLocal(_threadlocal, _defaults)


def _increase_depth():
    threadlocal.depth += 1
    threadlocal.prefix = _INDENT * threadlocal.depth


def _decrease_depth():
    threadlocal.depth -= 1
    threadlocal.prefix = _INDENT * threadlocal.depth

What I would expect: each threads gets a depth initialized to 0

这不是它的工作原理。只有创建全局threadlocal变量的线程将depth设置为0。大概是主线吧。必须分别初始化每个线程中的值

相关问题 更多 >