首页  >  文章  >  后端开发  >  如何在 Python 中使用多处理池优雅地处理键盘中断

如何在 Python 中使用多处理池优雅地处理键盘中断

Linda Hamilton
Linda Hamilton原创
2024-10-22 14:23:03600浏览

How to Gracefully Handle KeyboardInterrupt with Multiprocessing Pools in Python

多处理池中的键盘中断处理:Python 陷阱

在 Python 的多处理模块中,键盘中断事件似乎无法终止池中的工作进程。考虑代码片段:

<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 错误导致 KeyboardInterrupt 无法中断对 threading.Condition.wait() 的调用。

解决方法:

解决方法是指定超时用于池操作。将:

<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>

通过指定任意大的超时,可以有效地消除阻塞行为并允许立即处理中断。这将导致所有工作进程在按下 Ctrl C 时正常退出。

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

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn