LoginSignup
7
11

More than 5 years have passed since last update.

pythonのmultiprocessing Poolをctrl+c(KeyboardInterrupt)で終了したい

Posted at

問題

pythonのmultiprocessing Poolを、普通に書いて、実行中にctrl+cすると、プロセスが終了せず止まったままになる。

pool.py
import time
from multiprocessing import Pool

def worker(arg):
    print("process {}".format(arg))
    time.sleep(2)

if __name__ == '__main__':
    p = Pool(2)
    p.map(worker, range(6))
    p.close()

(上記のソースを実行中にCtrl+Cすると)

(略)
KeyboardInterrupt

(この状態で停止してしまう)

プロセスIDを指定してkillしても、ゾンビのようにpythonが復活してしまう。
なんとかCtrl+Cできれいに終了させたい。

原因

StackOverflowにまったく同じ悩みを抱えている方がいらっしゃった。
https://stackoverflow.com/questions/1408356/keyboard-interrupts-with-pythons-multiprocessing-pool

Poolの中で呼んでる処理にKeyboardInterruptの入力が伝達されず、wait関数がいつまでも待ち続けてしまうらしい。

解決方法

タイムアウトを設定してやるとOK。

p.map(worker, range(6))

p.map_async(worker, range(6)).get(9999999)

に置き変える。

7
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
11