from __future__ import with_statement import threading class synchonized(object): def __init__(self, obj=None): if obj is None: self._lock = None return if not hasattr(obj, '_kaa_synchonized_lock'): obj._kaa_synchonized_lock = threading.RLock() self._lock = obj._kaa_synchonized_lock def __enter__(self): self._lock.acquire() def __exit__(self, type, value, traceback): self._lock.release() def __call__(self, func): def call(obj, *args, **kwargs): if not hasattr(obj, '_kaa_synchonized_lock'): obj._kaa_synchonized_lock = threading.RLock() lock = obj._kaa_synchonized_lock lock.acquire() try: return func(obj, *args, **kwargs) finally: lock.release() return call class Test(object): def foo(self): with synchonized(self): print 5 @synchonized() def bar(self, x, y): print 1, x, y t = Test() t.bar(5, 9) t.foo() t2 = Test() t2.foo()