Skip to content

Instantly share code, notes, and snippets.

@J3ronimo
Last active October 5, 2018 08:32
Show Gist options
  • Save J3ronimo/6b1502365376da934bd916134bd45b46 to your computer and use it in GitHub Desktop.
Save J3ronimo/6b1502365376da934bd916134bd45b46 to your computer and use it in GitHub Desktop.
Simple Lock decorator for bound methods
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