Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Can I use class variables as thread locks?

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?

like image 289
Torsten Engelbrecht Avatar asked May 28 '13 09:05

Torsten Engelbrecht


1 Answers

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

like image 140
John La Rooy Avatar answered Sep 19 '22 15:09

John La Rooy