synchronized method

Max Ischenko max at ucmg.com.ua.remove.it
Tue Feb 10 07:54:32 EST 2004


Graham Dumpleton wrote:

>>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.

Hmm. I think you must be wrong:

 >>> def foo():
	try:
		return 1
	finally:
		print 'ok'

		
 >>> foo()
ok
1

> There is also the case that method isn't defined.

Indeed, thanks for pointing this out.

> Someone else was asking about this sort of thing back the end of January.
> The post is included below. As much as doing this sort of thing may sound
> like a good way of handling synchronisation, it still has its problems.

[ cut ]

I'll look into it.



More information about the Python-list mailing list