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测试服务器的开发中运行的:我还没有调整它以生成一个可以用普通线程演示的最小示例)
此实现解决了我的问题:
这不是它的工作原理。只有创建全局
threadlocal
变量的线程将depth
设置为0
。大概是主线吧。必须分别初始化每个线程中的值相关问题 更多 >
编程相关推荐