[Python-ideas] Protecting finally clauses of interruptions

Victor Stinner victor.stinner at gmail.com
Sat Apr 7 12:04:28 CEST 2012

> I'd like to propose a way to protect `finally` clauses from
> interruptions (either by KeyboardInterrupt or by timeout, or any other
> way).

With Python 3.3, you can easily write a context manager disabling
interruptions using signal.pthread_sigmask(). If a signal is send, the
signal will be waiting in a queue, and the signal handler will be
called when the signals are unblocked. (On some OSes, the signal
handler is not called immediatly.)

pthread_sigmask() only affects the current thread. If you have two
threads, and you block all signals in thread A, the C signal handler
will be called in the thread B. But if I remember correctly, the
Python signal handler is always called in the main thread.

pthread_sigmask() is not available on all platforms (e.g. not on
Windows), and some OSes have a poor support of signals+threads (e.g.
OpenBSD and old versions of FreeBSD).

Calling pthread_sigmask() twice (enter and exit the final block) has a
cost, I don't think that it should be done by default. It may also
have unexpected behaviours. I prefer to make it explicit.


You may hack ceval.c to not call the Python signal handler in a final
block, but system calls will still be interrupted (EINTR).


More information about the Python-ideas mailing list