exception from a thread

Diez B. Roggisch deets at nospam.web.de
Fri Jun 29 00:22:38 CEST 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

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

          self.running = False

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

while True:

    for t in threads:
        if not t.running:
           print "Not running anymor: %r" % t


More information about the Python-list mailing list