0
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 practice and I would normally use a lock.

However, django states that:

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).

I do not completely understand the above quotation because storing state variables is an atomic operation.

In my case I read and replace at the same time. The same quotation, reads that each view has an "independent state".

Is it safe to consider the use of a lock redundant?

Community
  • 1
  • 1
raratiru
  • 8,748
  • 4
  • 73
  • 113

1 Answers1

1

This instance cannot possibly be shared across threads, so there is no need for a lock here.

As the documentation you link to shows, each request is a thread-safe operation. As part of that, the ListView is instantiated for each request, and its get_context_data is called within that request. That means that the instantiation of MyClass is also only ever within a single thread.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895