killing thread ?

Peter Hansen peter at engcorp.com
Tue Feb 11 13:58:10 EST 2003


anton wilson wrote:
> 
> On Friday 24 January 2003 04:36 pm, Peter Hansen wrote:
> > I'd support a PEP that proposed being able to set a flag in
> > a thread or in the interpreter so that a SystemExit exception
> > would be thrown at the very next bytecode instruction that gets
> > executed.
> 
> I'm somewhat interested in attempting to do this myself. You have any ideas
> on how to communicate the kill message between threads? One way I can think
> of right now is with a global list of threads to be killed that get's checked
> in the interpreter loop. 
[...]
> The way you suggested would, in a non-cross-platform manner, set up a
> "A global signal handler then raises an exception in the
> target thread which gets handled the usual way." I'm guessing that for this
> to work, the thread that get's the signal would catch it in some imported c
> module and then rasise the SystemExit exception from within the module.
> Correct me if I'm wrong.

I believe you're wrong, although my idea was not very concrete, so
it's quite open to interpretation, so maybe you're right. ;-)

It's been a while since I looked at the interpreter, but I believe
it has direct knowledge of Python threads.  I believe it should 
therefore be possible to arrange for a flag that is checked, 
maybe only when the 'checkinterval' is reached (number of bytecode
instructions before a context switch is considered), and if
it's true, the exception is raised as though the next bytecode
instruction caused it.

The thread object itself could have the flag, so you don't need to
have a global "hit list" of threads with the added overhead of
checking the GIL.  Add a method to the thread class and you probably
have all you need to let another thread (or the thread itself,
if you like suicide) trigger the behaviour.

It would be 100% cross-platform, as it would be either pure Python,
or require only the (presumably already cross-platform) core thread
structure to support the flag, plus generic changes to the interpreter.

-Peter




More information about the Python-list mailing list