Created
June 11, 2014 10:13
-
-
Save ulises/858ad7432b4e6db738e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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