gpt4 book ai didi

python - 在 Python 中,在多线程程序中调用 os.waitpid 有什么缺点?

转载 作者:行者123 更新时间:2023-11-28 19:27:40 24 4
gpt4 key购买 nike

我听说在线程中调用 os.waitpid 时会出现问题。我还没有遇到过这样的问题(尤其是使用 os.WNOHANG 选项)。然而,我并没有太注意这种使用对性能的影响。

是否存在性能损失或任何其他应注意的问题?这是否与 os.waitpid(可能)使用信号有关?

不过,我看不出信号是如何关联的,否则(我想)我无法让 os.waitpid 在从非主线程调用时返回。

最佳答案

默认情况下,子进程死亡时,父进程会收到 SIGCHLD 信号。对调用 os.waitpid() 的关注可能来自于此。

如果您查看 Python“信号”模块文档,警告非常清楚:

Some care must be taken if both signals and threads are used in the same program. The fundamental thing to remember in using signals and threads simultaneously is: always perform signal() operations in the main thread of execution. Any thread can perform an alarm(), getsignal(), pause(), setitimer() or getitimer(); only the main thread can set a new signal handler, and the main thread will be the only one to receive signals (this is enforced by the Python signal module, even if the underlying thread implementation supports sending signals to individual threads). This means that signals can’t be used as a means of inter-thread communication. Use locks instead.

http://docs.python.org/library/signal.html

但是...如果您不理会 SIGCHLD 信号,那么您应该能够从线程中愉快地调用 os.waitpid()(或任何其他 os.wait() 变体)。

那么主要的缺点是,如果您想以任何方式取消操作,则需要将 os.waitpid() 与 WNOHANG 一起使用并定期轮询。如果您永远不需要取消 os.waitpid(),那么您可以在阻塞模式下调用它。

关于python - 在 Python 中,在多线程程序中调用 os.waitpid 有什么缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5691309/

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