Last active
June 14, 2022 20:17
-
-
Save ntim/6debf7547332a2bfef9c to your computer and use it in GitHub Desktop.
Multiprocessing queue with Ctrl-C interrupt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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