Thread terminate

Chris Kaynor ckaynor at zindagigames.com
Thu Aug 28 12:23:24 EDT 2014


On Thu, Aug 28, 2014 at 1:52 AM, Ervin Hegedüs <airween at gmail.com> wrote:
>
>  > In your case, you may want to just handle the exceptions inside the
> > thread's run() function directly. If that is not possible and you really
> > need to handle them inside the main thread, you would need to store off
> the
> > error data in a variable (either passed into the thread as the "args" or
> > "kwargs" arguments to the MyThread() call, or global or class variables)
> > then use mt.join() to wait for the thread(s) to exit.
>
> no, I don't need to handle it outside of thread - the point is
> when the exception raised in a running thread, then the exception
> be logged (that's no problem), and thread be stopped state, so
> the caller function is able to call the join() that thread.


In this case, all that needs to happen is for the thread's run function to
either throw an exception (as happens in the error case in your sample
code) or return.

The threading module will cause it to print any exception that occurs by
default.


>  > In the case of handling the problems in the main thread, your main
> thread
> > code would look something like:
> >
> > # Start all of the threads up-front.
> >
> > threads = []
> > for q in range(0, 10):
> >     mt = MyThread()
> >     mt.start() # NOT mt.run() - that does not do any threading!
> >     threads.append(mt)
> >
> > # Now wait for them to complete.
> >
> > for thread in threads:
> >     thread.join()
> >     # Check for the status of thread here. Possibly on the thread object,
> > which can be mutated in MyThread.run by assigning to members of self.
> >
>
> yes, the pseudo structure of my code is same as your here. But
> the now the problem is when an exception raised, that showed at
> stdout too, not just the log.
>

If what you want is to make sure the error is not printed to stderr, you'll
just need to make sure the thread's run function does not exit with an
exception. The simpliest way to do that would be to wrap the entire
thread's run function in a try...catch statement, like so:

class Thread(threading.Thread)

def run(self):

try:

 # Do your code here.

# You can also have more specific error-handling inside here if needed.

except Exception as err:

# Log your error here - you will be silencing it and therefore unable to
see it in the TTY!

# If you want to be able to handle the errors in the main thread, you could
run code like the following:

#self.err = err

 # Where you can check and access them on the main thread.

return # Optional if there is no other code outside the try...except.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140828/6a80e90e/attachment.html>


More information about the Python-list mailing list