Problem with Lock.aquire() and user defined exceptions

djw donald.welch.nospam at hp.com
Thu Oct 16 17:31:04 EDT 2003


I was able to figure out both these problems. They both boiled down to a
try: finally: block at a higher level. Any sort of exception that occured
in code called from this block was getting "swallowed up"... is there a way
to determine in a try: finally: what exception (if any) occured? This seems
like a really dangerous construct, kind of like a "naked" try: except: that
doesn't specify exactly what exceptions are to be caught. 

-Don


djw wrote:

> Greetings,
> 
> I am having some difficulty with some _single_ threaded code that
> happens to contain thread locking around some data structure access.
> There is locking code beacuse I am going to have another thread access
> the data in the next rev of the code.
> 
> Red Hat Linux 9, Python 2.2.1
> 
> 
> import thread
> 
> devices = None
> device_lock = None
> 
> def getDevice(d):
>      global devices, device_lock
>      val = None
>      print device_lock.locked() # prints 0
>      device_lock.acquire() # hangs (blocks)
>      try:
>          val = devices[d]
>      finally:
>          device_lock.release()
>      return val
> 
> def init():
>      global devices, device_lock
>      devices = {}
>      device_lock = thread.allocate_lock()
> 
> init()
> devices["foo"] = 1 # not the way the program really operates, but you
> get the idea
> x = getDevice("foo") # prints 0, then hangs
> 
> This code is a bit of a contrived excerpt, but you get the idea. When I
> run this code in the framework of my larger program,  the program prints
> 0 and then hangs on the acquire() call.
> 
> I might point out that this code is being called from a handler that is
> being called from asyncore, so there are several levels above this code
> (at least above getDevice()).
> 
> I am having a strangely similar, but different issue when I try to raise
> user defined exceptions in my code. If I define:
> 
> class DeviceError(Exception):
>      pass
> 
> and then:
> 
> raise DeviceError
> 
> somewhere in my code, my program hangs, requiring a kill from the shell.
> 
> Is there some fundamental thing I am doing wrong here? This is the first
> time I have ever gotten such unexpected results from a Python program
> and I'm at a loss.
> 
> Thanks,
> 
> Don





More information about the Python-list mailing list