我在我的程序中使用多处理模块进行并行处理,我想获取多进程之间的共享dict对象,我可以在多进程正常关闭时进行,但按CTRL + C时无法获取,我怎样才能实现我的目标?我的代码如下
#!/usr/bin/python
from multiprocessing import Process, Manager, Pool
import os
import signal
import time
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def run_worker(i,my_d):
print 'Work Started: %d %d' % (os.getpid(), i)
for j in range(5):
print j
tmp1 = str(i) + str(j)
my_d[tmp1] = j
time.sleep(1)
def main():
print "Initializng 3 workers"
pool = Pool(3, init_worker)
manager = Manager()
my_d = manager.dict()
try:
for i in range(3):
pool.apply_async(run_worker,args=(i,my_d))
pool.close()
pool.join()
print my_d
# When process is closed normally, I could get the my_d successfully
except KeyboardInterrupt:
print "Caught KeyboardInterrupt, terminating workers"
pool.terminate()
pool.join()
print my_d
#When process is closed by Ctrl+C, couldn't I get the my_d ?
if __name__ == "__main__":
main()