Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Conditional "With" Lock Design

I am trying to do some shared locking using with statements

def someMethod(self, hasLock = False):      with self.my_lock:          self.somethingElse(hasLock=True)   def somethingElse(self, hasLock = False):     #I want this to be conditional...     with self.my_lock:           print 'i hate hello worlds" 

That make sense? I basically only want to do the with if I don't already have the lock.

On top of being able to accomplish this, is it a bad design? Should I just acquire/release myself?

like image 679
Nix Avatar asked Mar 03 '11 19:03

Nix


People also ask

What does lock () do in Python?

Once a thread has acquired the lock, all subsequent attempts to acquire the lock are blocked until it is released. The lock can be released using the release() method. Calling the release() method on a lock, in an unlocked state, results in an error.

Are the lock type a condition object can associate with?

Condition Objects. A condition variable is always associated with some kind of lock; this can be passed in or one will be created by default. Passing one in is useful when several condition variables must share the same lock. The lock is part of the condition object: you don't have to track it separately.

How do you lock a variable in Python?

This can be achieved using a mutex lock provided by the threading. Lock class. The lock can be created and shared along with the shared list variable. Each time the values in the list are modified by threads in the task() function, the lock must be acquired, then released once the updates are complete.


1 Answers

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?

like image 141
FogleBird Avatar answered Oct 04 '22 18:10

FogleBird