Metaclasses, decorators, and synchronization

Michael Ekstrand mekstran at
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):
         except AttributeError:
             if not hasattr(self, '_sync_lock'):
                 self._sync_lock = threading.RLock()
         meth(self, *args, **kwargs)
     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?


More information about the Python-list mailing list