Scoped Lock

Jp Calderone exarkun at intarweb.us
Mon Jan 5 08:11:35 EST 2004


On Mon, Jan 05, 2004 at 01:40:01PM +0100, Daniel Dittmar wrote:
> Marco Bubke wrote:
> > This does not look nice to me. There should be something me easily.
> > Maybe that:
> >
> > def do_something() lock(mutex):
> >         #this stuff is locked by the mutex
> >
> > So you don't forget to release the lock.
> 
> You could create a class that locks the mutex in the constructor and unlocks
> it in the __del__ method.
> 
> class ScopedLock:
>     def __init__ (self, mutex):
>         self.mutex = mutex
>         mutex.acquire()
> 
>     def __del__ (self):
>         self.mutex.release ()
> 
> use as
> def do_something():
>     lock = ScopedLock (mutex)
>     # do something
>     # lock will be automatically released when returning
> 
> 
> This works only in the current implementation of CPython where local
> variables are usually (*) deleted when they fall out of scope.

  Notably, this fails if an exception is raised, since the lock remains in
the locals dictionary of one of the frame objects in the traceback. 
Definitely not desirable.

  Jp





More information about the Python-list mailing list