I came across some interesting articles on the subject of killing child threads from a main process. I had only done this before in C# .NET, so I assumed this was a regular feature of threads, but then I discovered that Python has no built-in way of doing this. Java used to, but the methods are deprecated now. Considering all this, I find it interesting that Microsoft allows you to do it anyway (not that Microsoft is exactly known for doing things The Right Way™)!
So the recommended way to kill a child thread is through the use of a boolean variable within the child thread instance itself. The thread should poll this variable regularly within its “run” method to determine whether or not the thread should stop itself.
That’s simple enough. Unfortunately, I find this to be an inadequate solution when dealing with blocking I/O calls, since you still have to wait for the function to return. I wonder how people get around things like this when writing GUI apps, which generally need to be responsive at all times…
Update: I have now discovered wx.lib.delayedresult. However, I have also discovered the hard way that widgets should never be updated by worker threads. Doing so results in strange errors and segfaults in GTK.
This is why you use one thread for GUI stuff and another (“worker”) thread for data processing or i/o.
Or use non-blocking i/o (http://www.kegel.com/dkftpbench/nonblocking.html)
that’s what i’m doing, but you still have to wait for the blocking function in the worker thread to finish before the thread will die. so as far as i can tell, there’s essentially no way to create a cancel button that cancels immediately.
i dont feel like writing non-blocking versions of all the built-in python libs. =P
The argument that killing child threads is dangerous is mostly down to the idea that you might leave resources unattended.
This is something of a non-issue in the .NET world though, as all Abort() on System.Thread does is raise a ThreadAbortException on the next scheduling of the specified thread.
Providing you haven’t done anything explicitly bad and evil (like catching the ThreadAbortException and carrying on regardless…) that exception will then cascade up through the call stack, and if you’ve used Try/Finally or ‘using’ blocks correctly, you’ll clean up nicely an exit.