[Tutor] Locking a specific variable (fwd)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Apr 24 20:33:33 CEST 2006


> # The way I would like to do it, so we have two different instances of 
> the same variable, and only # one function can access it at a time. If a 
> function comes to that variable and finds a lock on it, # it will wait 
> until the lock is released.  And the variable happens to be a queue

Hi Tino,

One way to do this is to add a level of indirection.

##############################################
class LockedVariable:
     def __init__(self, val):
         self.val = val
         self.internal_lock = RLock()

     def acquire(self):
         self.internal_lock.acquire()

     def release(self):
         self.internal_lock.release()

def with_lock(locked_variable, function):
     locked_variable.acquire()
     try:
         return function(locked_variable.val)
     finally:
         locked_variable.release()
##############################################

The idea is that this allows us to pair up values with individual locks. 
There's nothing that restricts us to having one lock per program.


If you have some experience with treating functions as values, the last 
function, with_lock(), might be useful.  It's meant to be used as:

#########################################################
## Pseudocode
def function_using_some_locked_resource(locked_resource):
     def actual_work(val):
         ## ...
     with_lock(locked_variable, actual_work)
#########################################################

with_lock() here tries to capture the mutual-exclusion abstraction, and 
might make programs a little less error prone: we'll never forget to 
release the lock, because it handles both resource acquiring and 
releasing.


More information about the Tutor mailing list