这是我的代码,它应该做一些与其他问题试图做的非常相似的事情,特别是这个图是相关的: f1 = 生产,f2 = f3 = 工人,f4 = 消费者。
我还没有尝试解决完美结束一切的问题,这不是这个问题的意义所在。我收到错误“RuntimeError:队列对象只能通过继承在进程之间共享”而且我不确定如何修复它。我只是想将队列传递给像 Go 的频道这样的函数,真的。这是代码。
import multiprocessing
def produce(n, queue):
for i in xrange(n):
queue.put(i)
def worker(in_queue, out_queue):
for i in iter( in_queue.get, None):
out_queue.put(i*i)
def consumer(queue):
ans = []
for i in iter( queue.get, None):
ans.append(i)
return ans
def main(n):
pool = multiprocessing.Pool(4)
in_queue = multiprocessing.Queue()
out_queue = multiprocessing.Queue()
pool.apply_async(produce, (n, in_queue))
for i in range(2):
pool.apply_async(worker, (in_queue, out_queue))
result = consumer(out_queue)
pool.close()
pool.join()
return result
main(200)
我将如何解决它?
有更简单的方法吗?
我试过Pool.map
了,但我想让这个工作。