Python のマルチプロセッシング プールで KeyboardInterrupt イベントを処理するにはどうすればよいですか? 以下に簡単な例を示します。
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()
上記のコードを実行すると、KeyboardInterrupt
を押す^C
と が発生しますが、プロセスはその時点で単にハングするため、外部で強制終了する必要があります。
^C
いつでも押して、すべてのプロセスを正常に終了できるようにしたいと考えています。