I've found this article which explains how to kill running multiprocessing code using ctr+c. Following code is fully working (it can be terminated it using ctrl+c):
#!/usr/bin/env python
# Copyright (c) 2011 John Reese
# Licensed under the MIT License
import multiprocessing
import os
import signal
import time
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def run_worker():
time.sleep(15)
def main():
print "Initializng 5 workers"
pool = multiprocessing.Pool(5, init_worker)
print "Starting 3 jobs of 15 seconds each"
for i in range(3):
pool.apply_async(run_worker)
try:
print "Waiting 10 seconds"
time.sleep(10)
except KeyboardInterrupt:
print "Caught KeyboardInterrupt, terminating workers"
pool.terminate()
pool.join()
else:
print "Quitting normally"
pool.close()
pool.join()
if __name__ == "__main__":
main()
The problem is that I use different functions from multiprocessing module. I do not know how they are different to previous approach, it just works for me (except that this example cannot be terminated it using ctrl+c). Here is the code which I've been trying to modify according above version (previous version without signal handling used to printing tracebacks when ctrl+c was hit):
#!/usr/bin/env python
from time import sleep
import signal
from multiprocessing import Pool
from multiprocessing import cpu_count
def init_worker(n):
signal.signal(signal.SIGINT, signal.SIG_IGN)
sleep(.5)
print "n = %d" % n
results_sent_back_to_parent = n * n
return results_sent_back_to_parent
if __name__ == '__main__':
try:
p = Pool(processes = cpu_count())
results = p.map(init_worker, range(50), chunksize = 10)
except KeyboardInterrupt:
pool.terminate()
pool.join()
print(results)
Questions:
- Why is ctrl+c working in first example but not in 2nd
- How to modify 2nd code that ctrl+c will work?
- How does both codes differ (I mean in context of multiprocessing, one uses e.g.
pool.apply_async
and anothermap
)?
EDIT
in reply to @user2386841
I've commented signal.signal(signal.SIGINT, signal.SIG_IGN)
in init_worker
and tried to add right after if __name__ == '__main__':
but id did not worked, the same when I added it as last line in try:
block
in reply to @ThomasWagenaar
It behaves exactly the same (I've also tried various locations for signal handler as mentioned above); numbers are printing despite hitting ctr+c
and the only possible way to kill the script is to send it to background using ctrl+z
and then killing with kill %1