Scoped Lock

Ype Kingma ykingma at accessforall.nl
Mon Jan 5 16:24:25 EST 2004


Marco Bubke wrote:

> Ype Kingma wrote:
> 
>> Marco Bubke wrote:
>> 
>>> Hi
>>> 
>>> There is the Lock object in the threading module.
>>> But there is no medode there I could aquire a scoped
>>> lock like:
>>> 
>>> mutex = threading.Lock()
>>> my_lock = mutex.scoped_acquire() # maybe scoped_lock()
>>> #now this stuff is locked
>>> 
>>> del mylock
>>> 
>>> #the lock is released.
>>> 
>>> def do_domething:
>>>   my_lock = mutex.scoped_acquire()
>>>   #now this stuff is locked
>>>   #the lock is released after its out of scope
>>> 
>>> 
>>> I have written this my own but I'm not sure there is a drawback
>>> because its looks so convinent. So I wonder why its not in
>>> the module?
>> 
>> Some reasons:
>> - What should happen when an exception happens during the locked stuff?
>> - It is possible pass a reference to the lock during the locked stuff,
>>   so although the lock goes out of local scope, there still might be
>>   a reference to it.
>> - The moment that __del__() is called is not guaranteed.
>> 
>> You can also do it like this:
>> 
>> mutex = threading.Lock()
>> mutex.acquire()
>> try:
>>     # now this stuff is locked
>> finally:
>>     mutex.release() # explicit is better than implicit
> 
> This does not look nice to me. There should be something me easily.

An elegant and easier way has been designed, see PEP 310,
mentioned in another post in this thread:
http://www.python.org/peps/pep-0310.html

However, one normally does not use locks so often that the
lightly verbose idiom needed to use them becomes a problem.

Regards,
Ype




More information about the Python-list mailing list