[Python-ideas] Thread stopping

Andrew Svetlov andrew.svetlov at gmail.com
Thu Mar 29 21:48:28 CEST 2012

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.

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

More information about the Python-ideas mailing list