如何在 Python 中使用多處理池優雅地處理鍵盤中斷

Linda Hamilton
發布: 2024-10-22 14:23:03
原創
603 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!