Skip to content

Instantly share code, notes, and snippets.

@danielhfrank
Created December 8, 2011 22:51
Show Gist options
  • Save danielhfrank/1449074 to your computer and use it in GitHub Desktop.
Save danielhfrank/1449074 to your computer and use it in GitHub Desktop.
MC Lock Decorator
#====== Decorator to use memcached for locking =======
def mc_lock(namespace, on_lock_failed) :
'''
This uses memcached to provide a lock on a key before performing some operation.
The first argument provided to the decorated function will be the key.
It will be preceded by $namespace to ensure uniqueness
on_lock_failed is a function that will be called if we fail to acquire the lock
'''
def my_decorator(func) :
def wrapped(*args, **kwargs) :
if not args:
raise Exception("You must pass an un-named arg to use mc_lock on!")
lock_mc_key = _utf8('%s.%s' % (namespace, args[0]))
if mc.add(lock_mc_key, 1, time=300):
try:
return func(*args, **kwargs)
finally:
mc.delete(lock_mc_key)
else:
on_lock_failed()
return wrapped
return my_decorator
# ====================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment