| Killing a blocking thread in python? |
It seems that there is no way of killing a blocking thread in python? The standard way of implementing thread death seems to be to implement an exit() method on the class which is the thread, and then call that when you want the thread to die. However, if the run() method of the thread class is blocking when you call exit(), then the thread doesn't get killed. I can't find a way of killing these threads cleanly on Linux -- does anyone have any hints?
posted at: 14:03 | path: /python | permanent link to this entry
-
#1
Chris
If you need to _actually_ kill the thread, AFAIK there's no way of doing it so that the thread will die immediately when blocked (a-la Java's Interrupts).
A way that comes to mind would be to write a function whose nett effect is this:
def apply_checkforexit(object_to_check,f,*a,**k):
z = f(*a,**k)
if object_to_check.killed:
raise ThreadKilledError
return z
and use this to make potentially blocking function calls (hopefully that code is self-explanatory), this would check for thread death before returning, and if the the thread is "killed" whilst blocking, the thread will die as soon as the function call completes. That would, of course, only be acceptable if you can wait for the thread to unblock itself -- using setDaemon and the like will ensure that the threads won't block program termination.
--
Finally, if you really need instant kill; try out the multiprocessing library that comes with Python 2.6 (or can probably be found elsewhere too) -- it's a drop-in replacement for threading, but uses OS processes instead of actual threads. You can just ask for a subprocess' PID, and kill it using standard methods.
