I was thinking about using a class variable as a thread lock, since I don't like to define a lock within the global variables and also want to prevent deadlock. Does this actually work? Example:
import threading
class A(object):
lock = threading.Lock()
a = 1
@classmethod
def increase_a(cls):
with cls.lock:
cls.a += 1
Considering I would not re-assign the A.lock
variable somewhere inside or outside the class, my assumption would be that it is treated the same as a global lock? Is this correct?
class B(A): pass
beA.lock == B.lock
ifB
will useA.increase
it will lead to lock since doubleA.lock.aquire(); B.lock.aquire() # deadlock A.lock is B.lock
. Valid pattern is replace metaclass (defualt type) with class initializing lock this will allow thread safe inheritance. Do not try use in this case RLock since it will lead to more complex bugs. – Hephaestus