gpt4 book ai didi

python - 为什么只有主线程可以在 Python 中设置信号处理程序

转载 作者:行者123 更新时间:2023-12-04 20:31:58 25 4
gpt4 key购买 nike

在python的信号处理语义中,只有主线程可以设置信号处理程序,只有主线程可以调用信号处理程序。

为什么要这样设计?

最佳答案

此注释出现在 cpython 源文件 signalmodule.c 中:

/* NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS

When threads are supported, we want the following semantics:

  • only the main thread can set a signal handler
  • any thread can get a signal handler
  • signals are only delivered to the main thread

I.e. we don't support "synchronous signals" like SIGFPE (catching
this doesn't make much sense in Python anyway) nor do we support
signals as a means of inter-thread communication, since not all
thread implementations support that (at least our thread library
doesn't).

We still have the problem that in some implementations signals
generated by the keyboard (e.g. SIGINT) are delivered to all
threads (e.g. SGI), while in others (e.g. Solaris) such signals are
delivered to one random thread (an intermediate possibility would
be to deliver it to the main thread -- POSIX?). For now, we have a working implementation that works in all three cases -- the handler ignores signals if getpid() isn't the same as in the main thread.

XXX This is a hack.

*/



我对此的理解是,设置信号处理程序的限制是为了简化 cpython 中信号处理的实现,避免必须处理操作系统级信号实现的差异。

关于python - 为什么只有主线程可以在 Python 中设置信号处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44151888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com