[Python-Dev] Status of thread cancellation

glyph at divmod.com glyph at divmod.com
Fri Mar 16 23:00:22 CET 2007

On 12:06 am, 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.

That's a perfectly reasonable use-case which doesn't require this 
feature at all ;).
>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.

If that's true, then the state-sharing features of threads aren't 
required, which is the right way to design concurrent software anyway.
>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.

The key distinction between threads and processes is the sharing of 
internal program state.
>How would you handle this situation?

Spawn a process, deliver the result via an event.

If you're allergic to event-driven programming, then you can spawn a 
process *in* a thread, and block in the thread on reading from the 
process's output, then kill the *process* and have that terminate the 
output, which terminates the read().  This is a lot like having a queue 
that you can put a "stop" object into, except the "file" interface 
provided by OSes is kind of crude.  Still no need to kill the thread.

At the end of the day though, you're writing a GUI in this use-case and 
so you typically *must* be cognizant of event-driven issues anyway. 
Many GUIs (even in the thread-happy world of Windows) aren't thread-safe 
except for a few specific data-exchange methods, which behave more or 
less like a queue.

One of the 35 different existing ways in which one can spawn a process 
from Python, I hope, will be sufficient for this case :).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-dev/attachments/20070316/131a3f48/attachment.html 

More information about the Python-Dev mailing list