All pastes #924626 Raw Edit

Someone

public text v1 · immutable
·published 2008-03-01 15:32 UTC
rendered paste body
from __future__ import with_statement
import thread
import threading

class synchronized(object):
    """
    synchronized decorator and with statement similar to synchronized
    in Java. When decorating a non-member function, a lock or any class
    inheriting from object must be provided.
    """
    def __init__(self, obj=None):
        if obj is None:
            # decorator in classes
            self._lock = None
            return
        if isinstance(obj, (threading._RLock, thread.LockType)):
            # decorator from functions
            self._lock = obj
            return
        # with statement or function decorator with object
        if not hasattr(obj, '_kaa_synchronized_lock'):
            obj._kaa_synchronized_lock = threading.RLock()
        self._lock = obj._kaa_synchronized_lock

    def __enter__(self):
        """
        with statement enter
        """
        self._lock.acquire()
        return self._lock

    def __exit__(self, type, value, traceback):
        """
        with statement exit
        """
        self._lock.release()
        return False

    def __call__(self, func):
        """
        decorator init
        """
        def call(*args, **kwargs):
            """
            decorator call
            """
            lock = self._lock
            if lock is None:
                # first parameter is self
                obj = args[0]
                if not hasattr(obj, '_kaa_synchronized_lock'):
                    obj._kaa_synchronized_lock = threading.RLock()
                lock = obj._kaa_synchronized_lock
            lock.acquire()
            try:
                return func(*args, **kwargs)
            finally:
                lock.release()
        return call



class Test(object):

    def foo(self):
        with synchronized(self):
            print 5

    @synchronized()
    def bar(self, x, y):
        print 1, x, y


lock = threading.Lock()

@synchronized(lock)
def foo():
    print 6

t = Test()

@synchronized(t)
def bar():
    print 7

t.bar(5, 9)
t.foo()

t2 = Test()
t2.foo()

foo()
bar()