How should threads be terminated? (related to 'Help with thread related tracebacks')

Peter Hansen peter at engcorp.com
Thu Jun 16 16:20:23 EDT 2005


Maxwell Hammer wrote:
> This is related to an earlier post 'Help with thread related
> tracebacks'...for which I have had no feedback yet :-(

If the question was well formulated, and it's been more than a couple of 
days, you should consider reposting.  It's very unusual for a post with 
such a subject (if it was a clear question) to get _no_ feedback around 
here.

> How should a thread complete i.e. how should it exit?

As with any function, just return...

> Reading the python online docs one gets the idea that simply returning is
> OK - but I'm not sure.
> Is it ok to do a sys.ext()? Use 'return' or just let them run out with no
> 'return' ???

sys.exit() merely raises a SystemExit exception.  In the main thread 
this will terminate the application (assuming no non-daemon threads are 
still running), while in a non-main thread it should simply be ignored.

If you aren't trying to exit from a function call within the thread, 
using "return" or just falling off the end of the run() method (if 
you've subclasses Thread) or the target function (if you used the 
"target=xxx" approach) is quite sufficient and acceptable.

Note that "return" is identical to "return None" which is identical to 
just falling off the end of a function in Python.  Some might consider a 
simple unadorned "return" to be the most expressive and readable.

-Peter



More information about the Python-list mailing list