[Python-ideas] Thread stopping

Serhiy Storchaka storchaka at gmail.com
Fri Mar 30 12:09:12 CEST 2012

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 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?).

P. S. I've had a crazy idea. What if we allow to raise any exception, 
not only ThreadInterruptionError, in another thread?

More information about the Python-ideas mailing list