如何在 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學習者快速成長!