Skip to content

Instantly share code, notes, and snippets.

@ntim
Last active June 14, 2022 20:17
Show Gist options
  • Save ntim/6debf7547332a2bfef9c to your computer and use it in GitHub Desktop.
Save ntim/6debf7547332a2bfef9c to your computer and use it in GitHub Desktop.
Multiprocessing queue with Ctrl-C interrupt
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from multiprocessing import Pool
import signal
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def run(i):
# ...
if __name__ == '__main__':
pool = Pool(3, init_worker)
try:
results = []
for idx in xrange(100):
results.append(pool.apply_async(run, (idx)))
while len(results) > 0:
result = results.pop(0)
result.get()
pool.close()
pool.join()
except KeyboardInterrupt:
print "Caught KeyboardInterrupt, terminating workers"
pool.terminate()
pool.join()
print "done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment