[Tutor] Exit a child thread using threading.Thread() object
Kent Johnson
kent37 at tds.net
Tue Jan 31 21:17:09 CET 2006
Bernard Lebel wrote:
> A quick question.
>
> I have started a child thread using the threading.Thread class. Is
> there any way to cleanly exit the child thread?
>
> What I mean by "cleanly" is for example if you use the
> thread.start_new() function to create a child thread, the function
> running in the child thread can call thread.exit() to terminate the
> thread.
>
> I could not find anything comparable in the Thread object's documentation.
Both thread.start_new() and threading.Thread wrap a callable object in a
new thread. For start_new(), the callable is a parameter passed to the
function. For threading.Thread, the callable can be passed as an
initialization parameter or by overriding Thread.run().
In any case, the thread runs until the wrapped method terminates, either
by a normal function return or by raising an uncaught exception. The
usual way to exit a thread is for the wrapped callable to return (just a
normal function return).
thread.exit() just raises SystemExit which terminates the callable with
an uncaught exception. You could probably do the same in a Thread by
raising SystemExit explicitly or calling sys.exit() (which raises
SystemExit for you). But just returning normally from the callable is
the usual way to exit a thread from within the thread.
If you want to stop a thread from another thread it is harder. The
cleanest way to do it is to set a flag that the running thread will
check. There are several recipes in the online cookbook that show how to
do this.
Kent
More information about the Tutor
mailing list