[Python-Dev] Questions about signal handling.

Yury Selivanov yselivanov.ml at gmail.com
Mon Sep 24 13:14:32 EDT 2018


On Fri, Sep 21, 2018 at 7:04 PM Eric Snow <ericsnowcurrently at gmail.com> wrote:
>
> Hi all,
>
> I've got a pretty good sense of how signal handling works in the
> runtime (i.e. via a dance with the eval loop), but still have some
> questions:
>
> 1. Why do we restrict calls to signal.signal() to the main thread?
> 2. Why must signal handlers run in the main thread?
> 3. Why does signal handling operate via the "pending calls" machinery
> and not distinctly?

Here's my take on this:

Handling signals in a multi-threaded program is hard. Some signals can
be delivered to an arbitrary thread, some to the one that caused them.
Posix provides lots of mechanisms to tune how signals are received (or
blocked) by individual threads, but (a) Python doesn't expose those
APIs, (b) using those APIs correctly is insanely hard.  By restricting
that we can only receive signals in the main thread we remove all that
complexity.  Restricting that signal.signal() can only be called from
the main thread just makes this API more consistent (and also IIRC
avoids weird sigaction() behaviour when it is called from different
threads within one program).

Next, you can only call reentrant functions in your signal handlers.
For instance, printf() function isn't safe to use.  Therefore one
common practice is to set a flag that a signal was received and check
it later (exactly what we do with the pending calls machinery).

Therefore, IMO, the current way we handle signals in Python is the
safest, most predictable, and most cross-platform option there is.
And changing how Python signals API works with threads in any way will
actually break the world.

Yury


More information about the Python-Dev mailing list