[Python-ideas] Thread stopping
Michael Foord
fuzzyman at gmail.com
Fri Mar 30 00:56:03 CEST 2012
On 29 March 2012 20:48, Andrew Svetlov <andrew.svetlov at gmail.com> wrote:
> 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.
>
I've worked with .NET where you can interrupt threads and it was very
useful. There is a complication though, if a thread is interrupted inside a
finally block then vital resource cleanup can be interrupted. The way .NET
solves this is to never raise the interrupt exception inside a finally
block. Once a finally block is completed a pending thread interrupt
exception will be raised.
The normal response to requests like this is for people to suggest that the
thread itself should check if it has been requested to stop - this is fine
for fine grained tasks but not for very coarse grained tasks.
Michael Foord
>
> Of course we cannot interrupt thread if it has been locked by C
> Extension call or just waiting for blocking IO.
> But, I think, the way to force stopping of some thread can be useful
> and has no incompatibility effect.
>
> The standard way to stop thread is the sending some message which is
> the signal to thread for termination.
> Pushing None or sentinel into thread message queue for example.
>
> Other variants:
> — check 'interrupted' state explicitly by call
> threading.current_thread().interrupted() than do what you want.
> — do the same as boost.threading does: check state in direct
> interruption point and locks if interruption is enabled.
>
> BTW, we can disable interruption mechanic by default and use it only
> if switched on by threading.enable_interruption()
>
> What do you think?
>
> --
> Thanks,
> Andrew Svetlov
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
--
http://www.voidspace.org.uk/
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/20120329/0aaac74e/attachment.html>
More information about the Python-ideas
mailing list