[Python-Dev] Status of thread cancellation

Josiah Carlson jcarlson at uci.edu
Fri Mar 16 01:53:09 CET 2007

Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> 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.

If the code is in Python, you can use sys.settrace to handle this. If
the code is in an extension module that a user has control over, having
a cancel_thread() function that is made available to Python, and having
your C code check the value of a single variable every few seconds could
do the same thing (even checking the value in a tight loop shouldn't
slow computations down significantly, branch prediction should be able
to make it a more or less zero-cost operation).  Yes, it can be tedious,
but at least the programmer can actually control cleanup in a reasonable

The only case that I have been able to come up with that is not covered
with these two is if you have no control over the C-level code, which
would be the case in a precompiled 3rd party extension or system call. 
In the system call case, I'm not sure there is a sane way to abort it on
all platforms, and I can just about guarantee that even if you *could*
kill a thread, doing so in 3rd party code (depending on the code) could
leave you in a questionable state (memory leaks, temporary files, broken
data structures, etc.).

It seems better to write to allow for cancellation, rather than adding a
big red STOP button to threads.

 - Josiah

More information about the Python-Dev mailing list