2009-09-18 52 views
11

鑑於this bug (Python Issue 4892),使人們產生了以下錯誤:Python 2.6中發送的連接對象在隊列/管材/等

>>> 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 

有誰知道的一種解決方法通過在隊列的連接對象?

謝謝。

回答

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報告中,讓其他人知道解決方法。

+0

很好的答案。絕對看起來是一個更好的選擇。 – 2011-01-18 03:05:29

+3

這是一個很好的答案,在2.6中爲我工作。然而,在2.7中,當函數'reduction.rebuild_connection' AKA'reduced [0]'被調用時,線程將無限期地阻塞。 – 2011-08-11 21:08:33

+0

我和@SamMagura有同樣的問題。有誰知道Python 2.7的解決方法嗎? – redrah 2012-08-30 15:14:47

7

這裏大概就是我所做的:

# 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)) 

希望幫助別人。這對我來說可以。

+0

謝謝,這是一個非常有用的回覆,我們真的被卡住了! – EdwardAndo 2015-01-28 17:12:17