Python: Can I use class variables as thread locks?

I was thinking about using a class variable as a thread lock, because I don't like to define a lock in global variables and also want to prevent a deadlock. Does it really work? Example:

import threading class A(object): lock = threading.Lock() a = 1 @classmethod def increase_a(cls): with cls.lock: cls.a += 1 

Given that I would not rewrite the A.lock variable somewhere inside or outside the class, my assumption would be that it is handled in the same way as a global lock? Is it correct?

+8
python multithreading
source share
1 answer

Of course. You want to have a lock link that is easy to get, and keeping it in the class is just fine.

You can call it __lock (to activate name mangling ), so it does not get confused with locks in subclasses A

+2
source share

All Articles