基于 Django Class 的视图:在此示例中,锁是否冗余?
Django Class-Based View: Would a lock be reduntant in this example?
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 is not a thread safe练习,我通常会使用锁。
但是,django states:
Each request served by a class-based view has an independent state;
therefore, it is safe to store state variables on the instance (i.e.,
self.foo = 3 is a thread-safe operation).
我不完全理解上面的引用,因为存储状态变量是和atomic operation。
在我的例子中,我同时阅读和替换。同样的引用,读到每个视图都有一个 "independent state".
考虑使用锁是多余的吗?
这个实例不可能跨线程共享,所以这里不需要锁。
正如您 link 显示的文档,每个请求都是线程安全操作。作为其中的一部分,ListView 为每个请求实例化,并在该请求中调用其 get_context_data
。这意味着 MyClass 的实例化也只能在单个线程中进行。
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 is not a thread safe练习,我通常会使用锁。
但是,django states:
Each request served by a class-based view has an independent state; therefore, it is safe to store state variables on the instance (i.e., self.foo = 3 is a thread-safe operation).
我不完全理解上面的引用,因为存储状态变量是和atomic operation。
在我的例子中,我同时阅读和替换。同样的引用,读到每个视图都有一个 "independent state".
考虑使用锁是多余的吗?
这个实例不可能跨线程共享,所以这里不需要锁。
正如您 link 显示的文档,每个请求都是线程安全操作。作为其中的一部分,ListView 为每个请求实例化,并在该请求中调用其 get_context_data
。这意味着 MyClass 的实例化也只能在单个线程中进行。