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?
Sure. You want to have a reference to the lock that's easy to get at, and storing it on the class is just fine.
You may want to call it __lock
(to activate name mangling) though, so it's not confused with locks in subclasses of A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With