鉴于this bug (Python Issue 4892),会产生以下错误:
>>> import multiprocessing
>>> multiprocessing.allow_connection_pickling()
>>> q = multiprocessing.Queue()
>>> p = multiprocessing.Pipe()
>>> q.put(p)
>>> q.get()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../python2.6/multiprocessing/queues.py", line 91, in get
res = self._recv()
TypeError: Required argument 'handle' (pos 1) not found
有没有人知道在队列上传递Connection对象的解决方法?
谢谢。
答案 0 :(得分:8)
以下是我的所作所为:
# Producer
from multiprocessing.reduction import reduce_connection
from multiprocessing import Pipe
# Producer and Consumer share the Queue we call queue
def handle(queue):
reader, writer = Pipe()
pickled_writer = pickle.dumps(reduce_connection(writer))
queue.put(pickled_writer)
和
# Consumer
from multiprocessing.reduction import rebuild_connection
def wait_for_request():
pickled_write = queue.get(block=True) # block=True isn't necessary, of course
upw = pickle.loads(pickled_writer) # unpickled writer
writer = upw[0](upw[1][0],upw[1][1],upw[1][2])
最后一行很神秘,来自以下内容:
>>> upw
(<function rebuild_connection at 0x1005df140>,
(('/var/folders/.../pymp-VhT3wX/listener-FKMB0W',
17, False), True, True))
希望能帮到别人。它对我来说很好。
答案 1 :(得分:8)
(我相信的是)一个更好的方法,经过一些游戏(我遇到了同样的问题。想要通过管道通过管道。)在发现这篇文章之前:
>>> from multiprocessing import Pipe, reduction
>>> i, o = Pipe()
>>> reduced = reduction.reduce_connection(i)
>>> newi = reduced[0](*reduced[1])
>>> newi.send("hi")
>>> o.recv()
'hi'
我不完全确定为什么这是以这种方式构建的(有人需要深入了解多处理的减少部分是什么)但它确实有效,并且不需要进行pickle导入。除此之外,它与它的作用非常接近,但更简单。我还把它扔进了python bug报告,以便其他人知道解决方法。