[Python-ideas] Interrupting threads

Charles-François Natali cf.natali at gmail.com
Mon Jan 28 00:59:12 CET 2013


> | Because it's unsafe.
>
> But the same can easily be true of a KeyboardInterrupt in the main
> thread in any multithreaded program.

Yes, that's why I don't catch KeyboardInterrupt, and only use it to
interrupt the execution of the program and leave it exit, unless it's
raised at specific places like reading from stdin...

> This is true if any other exception is raised also. MRAB's suggestion
> turns a thread interrupt into an exception, with some control for
> ignoring-but-detecting the exception around some places.

No, because properly written code is prepared to deal with exceptions
that the code is susceptible to throw.
This change would make it possible for an unrelated exception to be
thrown *at any point in the code*. Try writing safe and readable code
with this in mind: it's impossible (especially since the interruption
might be raise in the middle of the exception handling routine).

> That would amount to running the whole thread inside his context manager
> and polling the interrupt_occurred flag regularly.

This should be the default behavior: you only want to support
interruption at specific points in the code.

> On this basis, I'd be inclined to cast MRAB's suggestion as giving every
> Thread object a cancel() method. When heeding_interrupt is True, raise
> ThreadInterrupt. When heeding_interrupt is False, set
> interrupt_occurred.

That's still wrong: you want to test explicitly for interruption, or
throw interrupt exception at specific blocking calls (like sleep() or
acquire()).

Please have a look at the Java rationale and way of dealing with
interruption, you'll see why you want cooperative and specific
interruption support.

> It's in common use, and not obscure. I am a native speaker, and see no
> problem with it. Long standing word with a well known and defined
> meaning.

Really?
I know about sigprocmask(), pthread_sigmask(), SIG_IGN and SIG_BLOCK,
interrupt masking...
I couldn't find a single occurrence of "heed" in the POSIX specification.



More information about the Python-ideas mailing list