- Author:
- mwolgemuth
- Posted:
- January 23, 2009
- Language:
- Python
- Version:
- 1.0
- Score:
- 1 (after 1 ratings)
This decorator allows you to wrap class methods or module functions and synchronize access to them. It maintains a dict of locks with a key for each unique name of combined module name and method name. (Implementing class name is lost in decorator? Otherwise it would have class name too if available.)
Effectively it functions as a class level method synchronizer, with the lock handling completely hidden from the wrapped function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | from threading import Lock
_lock_table_lock = Lock()
_lock_table = {}
# decorate drops method attributes like .im_class? bleah
def synchronized_module_function():
""" Synchronization decorator. """
def decorate(f):
def new_func(*args, **kw):
lock = _get_lock_for_method(f)
lock.acquire()
try:
return f(*args, **kw)
finally:
lock.release()
return new_func
return decorate
def _get_lock_for_method(f):
# key from module class is from, func name -- would like class name but not available?
_lock_table_lock.acquire()
try:
key = "%s%s" % (f.__module__, f.__name__)
lock = None
try:
lock = _lock_table[key]
except KeyError:
lock = _lock_table[key] = Lock()
finally:
_lock_table_lock.release()
return lock
|
More like this
- Generate and render HTML Table by LLyaudet 5 days, 10 hours ago
- My firs Snippets by GutemaG 1 week, 1 day ago
- FileField having auto upload_to path by junaidmgithub 1 month, 2 weeks ago
- LazyPrimaryKeyRelatedField by LLyaudet 1 month, 3 weeks ago
- CacheInDictManager by LLyaudet 1 month, 3 weeks ago
Comments
Please login first before commenting.