Skip to content

Instantly share code, notes, and snippets.

@pright
Created November 12, 2016 09:06
Show Gist options
  • Select an option

  • Save pright/a002e944d65dc8d56cdcc02163aadeed to your computer and use it in GitHub Desktop.

Select an option

Save pright/a002e944d65dc8d56cdcc02163aadeed to your computer and use it in GitHub Desktop.
how to interrupt multiprocessing.Pool gently...
import multiprocessing
import time
import os
import signal
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def do_work(id):
print "do_work(%d) %d" % (os.getpid(), id)
time.sleep(5)
print "return(%d) %d" % (os.getpid(), id)
return id
def main():
pool = multiprocessing.Pool(4, init_worker)
output = []
try:
# Workaround 1
results = []
for i in xrange(10):
print "apply_async %d" % i
results.append(pool.apply_async(do_work, (i, )))
for r in results:
try:
r = r.get(0xffff)
except multiprocessing.TimeoutError:
print "timeout"
else:
output.append(r)
# Workaround 2
try:
results = pool.map_async(do_work, range(10, 20)).get(0xffff)
except multiprocessing.TimeoutError:
print "timeout"
else:
output += results
print "close"
pool.close()
pool.join()
except KeyboardInterrupt:
print "terminate"
pool.terminate()
pool.join()
print output
print "Done."
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment