Killing threads (was Re: Cancel or timeout a long running regular expression)

Antoon Pardon Antoon.Pardon at rece.vub.ac.be
Mon Sep 19 06:04:01 EDT 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

  http://docs.python.org/release/3.2.2/c-api/init.html

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:

  http://www.google.com/search?ie=UTF-8&oe=utf-8&q=python+recipe+PyThreadState_SetAsyncExc

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

  http://mail.python.org/pipermail/python-dev/2006-August/068158.html

about this. I don't know how it was finaly resolved.

-- 
Antoon Pardon



More information about the Python-list mailing list