Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from multiprocessing import Pool
- from time import sleep
- from sys import exit
- def slowly_square(i):
- sleep(1)
- return i*i
- def go():
- pool = Pool(8)
- try:
- results = pool.map(slowly_square, range(40))
- except KeyboardInterrupt:
- # **** THIS PART NEVER EXECUTES. ****
- pool.terminate()
- print "You cancelled the program!"
- sys.exit(1)
- print "nFinally, here are the results: ", results
- if __name__ == "__main__":
- go()
- import threading
- cond = threading.Condition(threading.Lock())
- cond.acquire()
- cond.wait(None)
- print "done"
- results = pool.map(slowly_square, range(40))
- results = pool.map_async(slowly_square, range(40)).get(9999999)
- from multiprocessing import Pool
- import time
- class KeyboardInterruptError(Exception): pass
- def f(x):
- try:
- time.sleep(x)
- return x
- except KeyboardInterrupt:
- raise KeyboardInterruptError()
- def main():
- p = Pool(processes=4)
- try:
- print 'starting the pool map'
- print p.map(f, range(10))
- p.close()
- print 'pool map complete'
- except KeyboardInterrupt:
- print 'got ^C while pool mapping, terminating the pool'
- p.terminate()
- print 'pool is terminated'
- except Exception, e:
- print 'got exception: %r, terminating the pool' % (e,)
- p.terminate()
- print 'pool is terminated'
- finally:
- print 'joining pool processes'
- p.join()
- print 'join complete'
- print 'the end'
- if __name__ == '__main__':
- main()
- staring the pool map
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- pool map complete
- joining pool processes
- join complete
- the end
- staring the pool map
- got ^C while pool mapping, terminating the pool
- pool is terminated
- joining pool processes
- join complete
- the end
- import signal
- ...
- def init_worker():
- signal.signal(signal.SIGINT, signal.SIG_IGN)
- ...
- def main()
- pool = multiprocessing.Pool(size, init_worker)
- ...
- except KeyboardInterrupt:
- pool.terminate()
- pool.wait()
- def slowly_square(i):
- try:
- sleep(1)
- return i * i
- except KeyboardInterrupt:
- print 'You EVIL bastard!'
- return 0
Advertisement
Add Comment
Please, Sign In to add comment