首頁  >  文章  >  後端開發  >  如何在 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