我希望一个长时间运行的进程通过一个队列(或类似的东西)返回其进度,该队列将被馈送到进度栏对话框。该过程完成后,我还需要结果。这里的测试示例以失败RuntimeError: Queue objects should only be shared between processes through inheritance。
RuntimeError: Queue objects should only be shared between processes through inheritance
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()
我已经能够得到这个使用单独的进程对象的工作(在这里我 很 alowed传递一个队列引用),但是我没有一个池来管理许多过程我想推出。有什么更好的模式建议吗?
以下代码似乎有效:
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(): manager = multiprocessing.Manager() q = manager.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()
请注意,队列是从manager.Queue()而不是multiprocessing.Queue()获得的。感谢Alex向我指出了这个方向。