[Python-ideas] Interrupting threads (original) (raw)
MRAB python at mrabarnett.plus.com
Mon Jan 28 18:20:50 CET 2013
- Previous message: [Python-ideas] Interrupting threads
- Next message: [Python-ideas] Interrupting threads
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
The point has been made that you don't want an interruption in the middle of an exception handling routine. That's true. You also don't want an interruption in the middle of a 'finally' block.
I think the problem here is that most of what I've been talking about regarding the context manager actually belongs to the 'try' statement; context managers are, after all, built on the 'try' statement.
In the following the flags, the exception and the thread's method have been renamed.
On entry to a 'try' statement, heed_thread_cancel is saved.
When an exception is raised, heed_thread_cancel is set to True. This ensures that normal exceptions take priority.
On entry to a 'finally' block, heed_thread_cancel is set to True. This ensures that the block will not be interrupted.
Execution will leave the 'try' statement in one of two ways:
Normal exit (i.e. the next statement to be executed will be the one after the 'try' statement). heed_thread_cancel is restored. If heed_thread_cancel is True and thread_cancelled is also True, then heed_thread_cancel is set to False and ThreadCancelled is raised.
Exception propagation (i.e. the 'try' statement has not handled the exception). The saved heed_thread_cancel is discarded (heed_thread_cancel remains False) and the propagation continues.
If the same logic applies to the keyboard interrupt (and the only real difference between ThreadCancelled and KeyboardInterrupt is that the former is triggered by the thread's 'cancel' method while the latter is triggered by the user pressing ^C or the equivalent), then the user pressing ^C will no longer interrupt the code in 'finally' blocks, breaking the clean-up code in context managers.
- Previous message: [Python-ideas] Interrupting threads
- Next message: [Python-ideas] Interrupting threads
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]