[Python-ideas] Thread stopping
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
> 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.
> 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?
> Andrew Svetlov
> Python-ideas mailing list
> Python-ideas at python.org
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...
More information about the Python-ideas