Skip to content

Instantly share code, notes, and snippets.

@ulises
Created June 11, 2014 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ulises/858ad7432b4e6db738e7 to your computer and use it in GitHub Desktop.
Save ulises/858ad7432b4e6db738e7 to your computer and use it in GitHub Desktop.
# from http://codereview.stackexchange.com/questions/42802/a-non-blocking-lock-decorator-in-python
def non_blocking_lock(fn):
"""Decorator. Prevents the function from being called multiple times simultaneously.
If thread A is executing the function and thread B attempts to call the
function, thread B will immediately receive a return value of None instead.
"""
locks = defaultdict(Lock)
@wraps(fn)
def locker(*args, **kwargs):
# args[0] is the clustername
lock = locks[args[0]]
if lock.acquire(False):
try:
return fn(*args, **kwargs)
finally:
lock.release()
return locker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment