Metaclasses, decorators, and synchronization

Victor Ng crankycoder at gmail.com
Mon Sep 26 05:30:21 CEST 2005


You could do it with a metaclass, but I think that's probably overkill.

It's not really efficient as it's doing test/set of an RLock all the
time, but hey - you didn't ask for efficient.  :)

      1 import threading
      2
      3 def synchronized(func):
      4     def innerMethod(self, *args, **kwargs):
      5         if not hasattr(self, '_sync_lock'):
      6             self._sync_lock = threading.RLock()
      7         self._sync_lock.acquire()
      8         print 'acquired %r' % self._sync_lock
      9         try:
     10             return func(self, *args, **kwargs)
     11         finally:
     12             self._sync_lock.release()
     13             print 'released %r' % self._sync_lock
     14     return innerMethod
     15
     16 class Foo(object):
     17     @synchronized
     18     def mySyncMethod(self):
     19         print "blah"
     20
     21
     22 f = Foo()
     23 f.mySyncMethod()

If you used a metaclass, you could save yourself the hassle of adding
a sync_lock in each instance, but you could also do that by just using
a plain old base class and making sure you call the base class's
__init__ to add in the sync lock.

vic


On 9/24/05, Michael Ekstrand <mekstran at scl.ameslab.gov> wrote:
> I've been googling around for a bit trying to find some mechanism for
> doing in Python something like Java's synchronized methods. In the
> decorators PEP, I see examples using a hypothetical synchronized
> decorator, but haven't stumbled across any actual implementation of
> such a decorator. I've also found Synch.py, but that seems to use
> pre-2.2 metaclasses from what I have read.
>
> Basically, what I want to do is something like this:
>
> class MyClass:
>      __metaclass__ = SynchronizedMeta
>      @synchronized
>      def my_sync_method():
>          pass
>
> where SychronizedMeta is some metaclass that implements synchronization
> logic for classes bearing some synchronized decorator (probably also
> defined by the module defining SynchronizedMeta).
>
> After looking in the Cheeseshop, the Python source distribution, and
> Google, I have not been able to find anything that implements this
> functionality. If there isn't anything, that's fine, I'll just write it
> myself (and hopefully be able to put it in the cheeseshop), but I'd
> rather avoid  duplicating effort solving previously solved problems...
> So, does anyone know of anything that alreaady does this? (or are there
> some serious problems with my design?)
>
> TIA,
> Michael
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
"Never attribute to malice that which can be adequately explained by
stupidity."  - Hanlon's Razor



More information about the Python-list mailing list