Killing threads (was Re: Cancel or timeout a long running regular expression)
Antoon.Pardon at rece.vub.ac.be
Mon Sep 19 12:04:01 CEST 2011
On Sun, Sep 18, 2011 at 07:35:01AM +1000, Chris Angelico wrote:
> On Sun, Sep 18, 2011 at 5:00 AM, Nobody <nobody at nowhere.com> wrote:
> Forking a thread to discuss threads.... ahem.
> Why is it that threads can't be killed? Do Python threads correspond
> to OS-provided threads (eg POSIX threads on Linux)? Every OS threading
> library I've seen has some way of killing threads, although I've not
> looked in detail into POSIX threads there (there seem to be two
> options, pthread_kill and pthread_cancel, that could be used, but I've
> not used either). If nothing else, it ought to be possible to
> implement a high level kill simply by setting a flag that the
> interpreter will inspect every few commands, the same way that
> KeyboardInterrupt is checked for.
> Is it just that nobody's implemented it, or is there a good reason for
> avoiding offering this sort of thing?
Python has a half baked solution to this. If you go to
You will find the following:
int PyThreadState_SetAsyncExc(long id, PyObject *exc)
Asynchronously raise an exception in a thread. The id argument is
the thread id of the target thread; exc is the exception object to be
raised. This function does not steal any references to exc. To prevent
naive misuse, you must write your own C extension to call this. Must be
called with the GIL held. Returns the number of thread states modified;
this is normally one, but will be zero if the thread id isn’t found. If
exc is NULL, the pending exception (if any) for the thread is cleared.
This raises no exceptions.
Some recipes can be found at:
However it this doesn't work 100% correctly. Last time I tried
using this, it didn't work with an exception instance but
only with an execption class as parameter. There was a discussion at
about this. I don't know how it was finaly resolved.
More information about the Python-list