Scoped Lock

Daniel Dittmar daniel.dittmar at sap.com
Mon Jan 5 13:40:01 CET 2004


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.

(*) usually: unless they are returned or added to another object

And I guess with metaclasses, you can achieve something like Java's
synchronized methods.

Daniel






More information about the Python-list mailing list