[Python-Dev] Status of thread cancellation

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Mar 16 01:06:56 CET 2007

glyph at divmod.com wrote:

> Can you suggest any use-cases for thread termination which will *not* 
> result in a completely broken and unpredictable heap after the thread 
> has died?

Suppose you have a GUI and you want to launch a
long-running computation without blocking the
user interface. You don't know how long it will
take, so you want the user to be able to cancel
it if he gets bored.

There's no single place in the code where you
could put in a check for cancellation. Sprinkling
such checks all over the place would be tedious,
or even impossible if large amounts of time are
spent in calls to a third-party library that
wasn't designed for such things.

Interaction with the rest of the program is
extremely limited -- some data is passed in,
it churns away, and some data is returned. It
doesn't matter what happens to its internal
state if it gets interrupted, as it's all going
to be thrown away.

In that situation, it doesn't seem unreasonable
to me to want to be able to just kill the thread.
I don't see how it could do any more harm than
using KeyboardInterrupt to kill a program,
because that's all it is -- a subprogram running
inside your main program.

How would you handle this situation?

> If you can think of such a case, are you sure it wouldn't be 
> better served by a set of threads communicating over queues and sending 
> 'Stop' objects to each other

If the thread is guaranteed to return to reading
from the queue within a bounded time, that's fine,
and it's the solution I would recommend in that
case. But not all cases are like that.


More information about the Python-Dev mailing list