Created
November 17, 2015 07:11
-
-
Save jeffrey4l/b3816a2c695dd04e6190 to your computer and use it in GitHub Desktop.
Interrupt the Python multiprocessing.Pool in graceful way
This file contains hidden or 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
| import multiprocessing | |
| from multiprocessing import Pool | |
| import time | |
| import signal | |
| def worker(): | |
| while True: | |
| print time.time() | |
| time.sleep(.5) | |
| def worker_init(): | |
| # ignore the SIGINI in sub process, just print a log | |
| def sig_int(signal_num, frame): | |
| print 'signal: %s' % signal_num | |
| signal.signal(signal.SIGINT, sig_int) | |
| pool = Pool(2, worker_init) | |
| result = pool.apply_async(worker) | |
| while True: | |
| try: | |
| result.get(0xfff) | |
| # catch TimeoutError and get again | |
| except multiprocessing.TimeoutError as ex: | |
| print 'timeout' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment