Tuesday, July 12, 2005

Python Locks

In the project I am developing right now there is a lot of threading done, and therefor some of the code needs to be protected by Mutexes. So, to save my self from finger-breaking, repetative task of lock aquiring and releasing, I wrote a small decorator (python 2.4) to help me out:
def lock_on(lock):
    def decorator(f):
        def wrapper(*args, **kwargs):
            lock.acquire()
            try:
                result = f(*args, **kwargs)
            finally:
                lock.release()
            return result
        return wrapper
    return decorator

Somewhere globally I have a hash of different mutexes, and when I need to create a critical section around some function, now all i have to do is this:
@locked_on(locks["some_mutex"])
def my_func(self):
    pass
Nifty!

No comments: