[Python-ideas] Thread stopping

Michael Foord fuzzyman at gmail.com
Sat Mar 31 12:33:30 CEST 2012

On 30 March 2012 11:09, Serhiy Storchaka <storchaka at gmail.com> wrote:

> 29.03.12 22:48, Andrew Svetlov написав(ла):
>  I propose to add Thread.interrupt() function.
>> th.interrupt() will set a flag in ThreadState structure.
>> When interpreter switches to next thread it will check that flag.
>> If flag is on then ThreadInterruptionError will be raised in thread
>> context.
>> If thread has blocked via threading locks (Lock, RLock, Condition,
>> Semaphore etc) — exception is raised also.
> At first glance this is a very attractive suggestion. But how about
> alternative GIL-less implementations? The interpreter can execute some
> threads at the same time.
> Java has a similar mechanism Thread.interrupt(), but that works only if
> the thread has blocked via threading locks. There is a stronger
> Thread.stop(), but it is recognized as unsafe and is deprecated.

It is "unsafe" because it can interrupt finally blocks - so it is
impossible to protect resource cleanup from thread interruptions. Java
solved this problem by deprecating thread interrupting - .NET solved it by
ensuring that a thread interrupt can't happen in a finally block (so it is
"safe"). The .NET solution is better. :-)

> It would be wrong to say that this is the way to *force* stopping of some
> thread. ThreadInterruptionError can and should be caught in some cases.
>  BTW, we can disable interruption mechanic by default and use it only
>> if switched on by threading.enable_interruption(**)
> And we need context manager for noninterrable critical sections (or for
> interrable non-critical sections?).

"Critical section" has a particular meaning, and by raising the exception
at the interpreter level (and not using the OS thread killing) we can
ensure critical sections can't be interrupted. If you just mean "important
sections" then preventing thread interrupts in a finally block provides one
mechanism for this. An "uninterruptable context manager" would be nice -
but would probably need extra vm support and isn't essential.


> P. S. I've had a crazy idea. What if we allow to raise any exception, not
> only ThreadInterruptionError, in another thread?
> ______________________________**_________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/**mailman/listinfo/python-ideas<http://mail.python.org/mailman/listinfo/python-ideas>



May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120331/b98c47d0/attachment.html>

More information about the Python-ideas mailing list