【发布时间】:2017-10-12 04:07:05
【问题描述】:
class MyView(ListView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
a_class = MyClass()
context['...'] = a_class.is_a_lock_reduntant_here()
return context
class MyClass(object):
def __init__(self):
self.counter = 0
def is_a_lock_reduntant_here(self):
return self.counter += 1
The above 不是thread safe 的做法,我通常会使用锁。
但是,django states 那:
基于类的视图服务的每个请求都有一个独立的状态; 因此,在实例上存储状态变量是安全的(即, self.foo = 3 是线程安全的操作)。
我不完全理解上面的引用,因为存储状态变量是atomic operation。
就我而言,我同时阅读和替换。同样的引文,读作每个视图都有一个“独立状态”。
考虑使用多余的锁是否安全?
【问题讨论】:
标签: python django django-views python-multithreading django-class-based-views