[Python-ideas] Interrupting threads

Charles-François Natali cf.natali at gmail.com
Sun Jan 27 09:58:03 CET 2013


> It's possible to interrupt the main thread using KeyboardInterrupt, so
> why shouldn't it be possible to do something similar to a thread?

Because it's unsafe.
Allowing asynchronous interruptions at any point in the code is
calling for trouble: in a multi-threaded program, if you interrupt a
thread in the middle of a critical section, there's a high chance that
the invariants protected in this critical section won't hold. So
basically, the object/structure will be in an unusable state, which
will lead to random failures at some point in the future.

> Actually, there's more to it than that because sometimes you don't want
> a section of code to be interrupted.

Actually it's exactly the opposite: you only want to handle
interruption at very specific points in the code, so that the rollback
and interruption logic is tractable.

Also, as noted by Guido, it's basically useless because neither
sleep() nor lock acquisition can be interrupted - at least in the
current implementation -  and those are likely the calls you'd like to
interrupt.

FWIW, Java has a Thread.Stop() method that more or less does what
you're suggesting. It was quickly depreciated because it's inherently
unsafe: the right way to do it is through a cooperative form of
interruption, with an interruption exception that can be thrown at
specific points in the code (and a per-thread interrupt status flag
that can be checked explicitly, and which is checked implicitly when
entering an interruptible method).
See the rationale here:
http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

> So here's what I'd like to suggest:
>
> 1. There's a private thread-specific flag called 'interrupt_occurred'.
>
> 2. There's a private thread-specific flag called 'heeding_interrupt'.
>
> 3. There's a context manager called 'heed_interrupt'.

I'm not a native speaker, and I had never heard about the 'heed' verb
before, had to look it up in the dictionary :-)



More information about the Python-ideas mailing list