exception from a thread

Diez B. Roggisch deets at nospam.web.de
Thu Jun 28 18:22:38 EDT 2007


_spitFIRE schrieb:
> assume a scenario, where there is a class that for doing some work,
> spawns lot of threads.
> 
> class X:
>     def __init__(self):
>         # Spawns some threads to
>         # do some work
> 
> now, assuming that at least one of the threads encounters a problem
> while doing work and throws an exception. Would I be able to handle
> that error in the caller class? When I try to do this, I see that the
> errors thrown by the threads never cascade to this caller :(

Exactly. Because they are different threads - the very essence of them 
is each of them having their own stacks.

Depending on what you do in the main-thread, you can do something like this:


class Worker(Thread):
    def __init__(self):
       ...
       self.running = False
       ...
       self.start()



    def run(self):
       self.running = True
       try:
          ... # work

       finally:
          self.running = False


In the main-thread, you test for each thread if it's still running.

while True:

    time.sleep(.1)
    for t in threads:
        if not t.running:
           print "Not running anymor: %r" % t

Diez



More information about the Python-list mailing list