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'
我所期望的是:每个线程都有一个... depth
初始化为 0
,并且修改只在该线程中可见。
为什么定义的属性在 threadlocal
线程中无法访问?
(这段代码是在django测试服务器的开发中运行的。我还没有对它进行调整,以产生一个可以用普通线程演示的最小例子。)
我期望的是:每个线程都得到一个
depth
初始化为0
不是这样的。只有创建你的全局的线程 threadlocal
变量组 depth
到 0
. 大概是主线程。你必须分别在每个线程中初始化这个值。
这个实现解决了我的问题。
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