Exceptions and locks

brianr at liffe.com brianr at liffe.com
Wed Apr 11 09:05:51 EDT 2001


matt at mondoinfo.com (Matthew Dixon Cowles) writes:

> On Tue, 10 Apr 2001 18:55:36 +0200, Michael Ströder
> <michael at stroeder.com> wrote:
> 
> >I'm currently doing something like this code below to make sure that
> >locks are released also in case of any exception raised:
> >
> >my_lock = threading.Lock()
> >
> >my_lock.acquire()
> >try:
> >  ..some single action..
> >except:
> >  my_lock.release()
> >  raise
> >my_lock.release()
> >
> >But this looks crude to me. Any more elegant way of doing this?
> 
> This is just the sort of situation that the try...finally sequence was
> designed for. See:
> 
> http://www.python.org/doc/current/ref/try.html
> 
> and have a look at the last two paragraphs.
> 
> Regards,
> Matt

In a similar vein, would the following work? :

class Guard:
	def __init__(self, Lock lock):
		self.lock = lock
		if not self.lock.acquire() == 1:
			raise RuntimeError, "Failed to acquire lock";
	def __del__(self):
		self.lock.release()

my_lock = threading.Lock()

def my_function():
        global my_lock
        g = Guard(my_lock)
        do_stuff_that_might_raise_an_exception()

-- 
Brian Raven
    switch (ref $@) {
    OverflowError =>
	warn "Dam needs to be drained";
    DomainError =>



More information about the Python-list mailing list