首頁  >  文章  >  後端開發  >  如何在 Python 的多處理池中處理鍵盤中斷?

如何在 Python 的多處理池中處理鍵盤中斷?

Susan Sarandon
Susan Sarandon原創
2024-10-22 14:22:03252瀏覽

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn