Python lock decorator
Here is small code snippet implementing python decorator for locking. I wrote the code for use with celery workers - workers read and modify shared dictionary and I need to keep this operations synced, so each method which is working with dictionary are decorated with synchronized decorator:
from multiprocessing import Manager manager = Manager() plock = manager.Lock() shared_dict = manager.dict() def synchronized(lock=plock): '''Sync decorator.''' def wrap(f): def new_function(*args, **kw): ret = None have_lock = False try: have_lock = lock.acquire() if have_lock: print 'Have lock' ret = f(*args, **kw) finally: if have_lock: print 'Releasing lock' lock.release() return ret return new_function return wrap













