Skip to content

Instantly share code, notes, and snippets.

@aidilfbk
Created August 11, 2015 10:51
Show Gist options
  • Save aidilfbk/1c347f825e79a17f3f92 to your computer and use it in GitHub Desktop.
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)
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