【问题标题】:Django Class-Based View: Would a lock be reduntant in this example?Django 基于类的视图:在这个例子中,锁会是多余的吗?
【发布时间】: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


    【解决方案1】:

    这个实例不可能跨线程共享,所以这里不需要锁。

    正如您链接到的文档所示,每个请求都是线程安全的操作。作为其中的一部分,将为每个请求实例化 ListView,并在该请求中调用其 get_context_data。这意味着 MyClass 的实例化也只能在单个线程中进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-22
      • 2014-07-04
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      相关资源
      最近更新 更多