Created
August 11, 2015 10:51
-
-
Save aidilfbk/1c347f825e79a17f3f92 to your computer and use it in GitHub Desktop.
Function decorator that causes multiple calls to the same function from multiple threads to wait on one thread to actually perform the function. Works with recursive functions (via threading.RLock)
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
import threading | |
def multithread_method_sync(method): | |
rlock = threading.RLock() | |
revent = threading.Event() | |
# result has to be a list because of Python closure weirdness | |
result = [None] | |
def callable(*args, **kwargs): | |
if rlock.acquire(blocking=False): | |
if rlock._RLock__count == 1: | |
revent.clear() | |
result[0] = method(*args, **kwargs) | |
rlock.release() | |
if rlock._RLock__count == 0: | |
revent.set() | |
else: | |
revent.wait() | |
return result[0] | |
return callable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment