decorator to synchronize method at class / module level

 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

  1. Javascript Chain Select Widget by ogo 4 years, 11 months ago
  2. Model Locking Mixin & Decorator (MySQL Advisory Locks) by pio 1 year, 12 months ago
  3. Controller Class for Views by jovialbard 1 month ago
  4. HttpMethodsMiddleware by hawkeye 6 years, 1 month ago
  5. Nested commit_on_success by rfk 4 years, 2 months ago

Comments

(Forgotten your password?)