synchronized method

Peter Hansen peter at engcorp.com
Tue Feb 10 17:38:46 CET 2004


Graham Dumpleton wrote:
> 
> Max Ischenko <max at ucmg.com.ua.remove.it> wrote in message news:<c0a1mt$v79$1 at hyppo.gu.net>...
> > Hi,
> >
> > I wrote simple implementation of the "synchronized" methods (a-la Java),
> > could you please check if it is OK:
> >
> > def synchronized(method):
> >
> >      """
> >      Guards method execution, similar to Java's synchronized keyword.
> >
> >      The class which uses this method, is required to have a
> >      L{threading.Lock} primitive as an attribute named 'lock'.
> >      """
> >
> >      def wrapper(self, *args):
> >          self.lock.acquire()
> >          try:
> >              return method(self, *args)
> >          finally:
> >              self.lock.release()
> >      return wrapper
> 
> Under normal execution the lock will not be released because you return
> from the try clause. There is also the case that method isn't defined.

If that were true, the finally clause would be pretty useless in many
cases.  (Try it out yourself: it will work properly.)

Also, isn't "method" defined as the argument to the synchronized()
function at the top?

To me, this looks like a pretty reasonable approach to handling
the problem as defined.

-Peter



More information about the Python-list mailing list