2013-05-21 76 views
2

我有這個使用多處理映射的簡單例子。但即使如此,我也無法正確運行。多處理映射引發異常

import multiprocessing 

p = multiprocessing.Pool() 

rere = range(50) 
print p.map(lambda x: x+1, rere) 

它將打印此異常:

Exception in thread Thread-3: 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/threading.py", line 808, in __bootstrap_inner 
    self.run() 
    File "/usr/lib/python2.7/threading.py", line 761, in run 
    self.__target(*self.__args, **self.__kwargs) 
    File "/usr/lib/python2.7/multiprocessing/pool.py", line 342, in _handle_tasks 
    put(task) 
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed 

並且不能使用Ctrl + C終止。

我應該如何解決我的例子,使其工作?

+0

是啊,我跳槍對不起。它與multiprocessing.pool.map的工作方式有關,「lambda x:x + 1」部分必須是pickleable,而不是函數,我們都需要更多的實驗! – TehTris

+2

http://stackoverflow.com/questions/8804830/python-multiprocessing-pickling-error?rq=1檢查一下,它幾乎完全相同 – TehTris

+0

聲明函數爲模塊中的頂層我得到這個: AttributeError: 'module'對象沒有屬性'f'(當然我的函數被稱爲f,並聲稱它不存在是由於某種原因)。 – LtWorf

回答

1

行,所以從我的研究,多的陌生的世界...

你現在的樣子試圖做到這一點,是遠遠不夠的。下文介紹了我如何設法實現它。

import multiprocessing as mp 
import time 

def theGenerator(): 
    for number in xrange(10): 
     yield number 

def processNumber(x): 
    return x*2 

def multiprocessThings(): 
    pool = mp.Pool() 
    gen = theGenerator() 
    result = pool.map(processNumber, gen) 
    print result 

if __name__ == "__main__": 
    multiprocessThings() 
    time.sleep(10) 

將它保存到任何地方,然後雙擊它。

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 

顯然這種類型的東西不會在解釋器中出於某種原因。

+0

謝謝,這個作品! (並且我不會雙擊,我使用命令行)。 – LtWorf

+0

沒問題!我也在這裏學習^ _ ^。它的種種準備工作 - 可以將它修改爲任何你想要的,不應該做太多的工作。 – TehTris

+0

我剛剛發現的另一件事....非常重要的是要確保無論你的函數是什麼(在我的例子中它的'processNumber()')確保它是TOP級別!出於某種原因,這非常重要。 – TehTris