Terminating a thread from the parent

Peter Hansen peter at engcorp.com
Mon May 23 15:09:56 EDT 2005


DE wrote:
> I have an app with embedded Python. Python scripts create their own
> threads and I need to terminate these threads at the point where the
> user wants to leave the application. I use threading.Thread as base
> classes.
> 
> I have tried to use call the join method of the python thread objects
> from C++. But although the call succeeds, the threads don't exit.

join() waits until the thread terminates, but it doesn't cause it to 
terminate.

> What is the proper way of doing this ? (e.g. how does the python shell
> do this ? )

You have to poll for a termination request in the thread's main loop, 
and have the thread terminate itself (by returning from the target 
function or from the run() method, depending on which technique you used 
to create the Thread in the first place).  Threads cannot be forcibly 
terminated**.

There are numerous examples of this in the archives and probably a 
Cookbook recipe or two about it, if you look.  Otherwise someone can 
post an example here.

-Peter

** The exception is Threads on which .setDaemon(True) has been called, 
which will terminate immediately when the main thread exits (i.e. when 
the entire process terminates), though that might not be helpful to you 
in your particular situation.



More information about the Python-list mailing list