Metaclasses, decorators, and synchronization

Michael Ekstrand mekstran at scl.ameslab.gov
Mon Sep 26 22:00:46 CEST 2005


On Sep 26, 2005, at 2:16 PM, Tom Anderson wrote:
> You could define a meta-lock, and use that to protect the
> lock-installation action.

Something like this (not yet tested):

import threading

global_lock = threading.Lock()

def synchronized(meth):
     def inner(self, *args, **kwargs):
         try:
             self._sync_lock.acquire()
         except AttributeError:
             global_lock.acquire()
             if not hasattr(self, '_sync_lock'):
                 self._sync_lock = threading.RLock()
             self._sync_lock.acquire()
             global_lock.release()
         meth(self, *args, **kwargs)
         self._sync_lock.release()
     return inner

I don't think this solution has any race conditions (hence the re-check 
of the existence of _sync_lock), and I've tried to optimize it for the 
common case in my project (calling the method after the lock has been 
put in place - that will happen much more than a call to a synchronized 
method of a fresh object).

As I said, I'm kinda new to this threading stuff... is there anything 
I'm missing in this implementation?

-Michael




More information about the Python-list mailing list