目的是想在主进程中随时终止子进程的执行 目前的代码长这样 有个问题是如果我 Ctrl-C 的话 所有的子进程虽然会正常退出 但是主进程会一直挂起在 pool.join()上 求解决方案~
#!/usr/bin/env python2
from __future__ import print_function
import time
import signal
import logging
from multiprocessing import Manager
from multiprocessing.pool import Pool
from multiprocessing.queues import Queue
def Fn(n, q, ns):
if ns.done:
return
try:
q.put(n)
finally:
return
def main():
handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
pool = Pool(processes=5)
signal.signal(signal.SIGINT, handler)
total = 10000
manager = Manager()
q = manager.Queue()
ns = manager.Namespace()
ns.done = False
for n in range(total):
pool.apply_async(Fn, args=(n, q, ns))
pool.close()
try:
received = 0
while received != total:
n = q.get(60)
print('get {} from queue'.format(n))
received += 1
except KeyboardInterrupt:
ns.done = True
pass
finally:
pool.join()
if __name__ == '__main__':
main()
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.