Python Conditional “With” Lock Design

后端 未结 5 1972
孤独总比滥情好
孤独总比滥情好 2020-12-15 16:48

I am trying to do some shared locking using with statements

def someMethod(self, hasLock = False):
     with self.my_lock:
         self.somethingElse(hasLoc         


        
5条回答
  •  庸人自扰
    2020-12-15 17:42

    Just use a threading.RLock which is re-entrant meaning it can be acquired multiple times by the same thread.

    http://docs.python.org/library/threading.html#rlock-objects

    For clarity, the RLock is used in the with statements, just like in your sample code:

    lock = threading.RLock()
    
    def func1():
        with lock:
            func2()
    
    def func2():
        with lock: # this does not block even though the lock is acquired already
            print 'hello world'
    

    As far as whether or not this is bad design, we'd need more context. Why both of the functions need to acquire the lock? When is func2 called by something other than func1?

提交回复
热议问题