如何在 Python 的多处理池中处理键盘中断?

Susan Sarandon
发布: 2024-10-22 14:22:03
原创
261 人浏览过

How to Handle Keyboard Interrupts in Python's Multiprocessing Pool?

在 Python 的多处理池中处理键盘中断

在 Python 的多处理模块中,Pool 类提供了一种在多个进程之间分配任务的便捷方法。然而,处理池中的 KeyboardInterrupt 事件可能具有挑战性,如代码片段所示:

<code class="python">from multiprocessing import Pool
from time import sleep
from sys import exit

def slowly_square(i):
    sleep(1)
    return i*i

def go():
    pool = Pool(8)
    try:
        results = pool.map(slowly_square, range(40))
    except KeyboardInterrupt:
        # **** THIS PART NEVER EXECUTES. ****
        pool.terminate()
        print "You cancelled the program!"
        sys.exit(1)
    print "\nFinally, here are the results: ", results

if __name__ == "__main__":
    go()</code>
登录后复制

运行此代码时,按 Ctrl C 不会触发清理过程,从而使子进程无限期地运行。要解决此问题,请考虑以下解决方法:

代码中观察到的行为是 Python 错误的结果。在 threading.Condition.wait() 中等待条件时,不会发送 KeyboardInterrupt。由于 Pool.map() 内部使用条件等待,因此永远不会收到中断。

解决方案是使用 Pool.map_async(),它允许指定超时。通过设置足够长的超时时间(例如9999999),我们可以保证在合理的时间内触发中断。

因此,将:

<code class="python">    results = pool.map(slowly_square, range(40))</code>
登录后复制

替换为:

<code class="python">    results = pool.map_async(slowly_square, range(40)).get(9999999)</code>
登录后复制

此解决方法提供了一种在多处理池中优雅地处理键盘中断事件的方法,允许在用户取消程序时终止所有子进程。

以上是如何在 Python 的多处理池中处理键盘中断?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!