参考:http://stackoverflow.com/questions/9908781/sharing-a-result-queue-among-several-processes
默认情况下,使用multiprocess.Queue()只是在两个进程之间进行通信,如下示例:
import multiprocessing, time def task(args): count = args[0] queue = args[1] for i in xrange(count): queue.put("%d mississippi" % i) return "Done" def main(): q = multiprocessing.Queue() pool = multiprocessing.Pool() result = pool.map_async(task, [(x, q) for x in range(10)]) time.sleep(1) while not q.empty(): print q.get() print result.get() if __name__ == "__main__": main()
如何在多进程间共享queue呢?
我们可以尝试使用multiprocessing.Manager来管理队列,并让不同的进程可以访问它。
解决方案如下:
import multiprocessing def worker(name, que): que.put("%d is done" % name) if __name__ == '__main__': pool = multiprocessing.Pool(processes=3) m = multiprocessing.Manager() q = m.Queue() workers = pool.apply_async(worker, (33, q))
文章的脚注信息由WordPress的wp-posturl插件自动生成