Last active
October 5, 2018 08:32
-
-
Save J3ronimo/6b1502365376da934bd916134bd45b46 to your computer and use it in GitHub Desktop.
Simple Lock decorator for bound methods
This file contains hidden or 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 | |
import functools | |
def with_lock(func): | |
""" Synchronization decorator applicable to bound methods, which | |
creates a threading.Lock for the decorated function, which is then acquired | |
on every call to the method. | |
Locks created will be stored in the dict self._func_locks. """ | |
@functools.wraps(func) | |
def wrapped(self, *args, **kwargs): | |
try: | |
lock = self._func_locks[func] | |
except AttributeError: | |
# self._func_locks doesnt exist yet | |
self._func_locks = {} | |
lock = self._func_locks[func] = threading.Lock() | |
except KeyError: | |
# self._func_locks[func] doesnt exist yet | |
lock = self._func_locks[func] = threading.Lock() | |
lock.acquire() | |
try: | |
return func(self, *args, **kwargs) | |
finally: | |
lock.release() | |
return wrapped |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment