2014-12-03 35 views
0

當我試圖用Python語言編寫的利用多重簡單的測試程序返回的自定義對象。我正在使用Pool.map()。對此,我傳遞了應該由子進程調用的方法。 它正常工作,我得到預期的結果時,返回類型爲蟒蛇內置類型如字符串,日期時間等 然而,當我使用自定義的類作爲返回類型,我的過程只是掛起。不知道如果我做的是正確的事情,任何建議將不勝感激。這裏是我的代碼如下:無法使用Python的游泳池地圖方法

from multiprocessing import Pool 
from multiprocessing.pool import ApplyResult 
import time 
import os 
import logging 
import multiprocessing 
import sys 


class C(object): 

    def __init__(self, a, b=1): 
     self.a = a 
     self.b = b   


    def f(self, name):    
     time.sleep(2) 

     #Doing some processing using custom classes 
     #and generating a result of custom type 

     x = someMethodInCustomClass() 

     # x now has list of list of custom objects eg x =[[c1,c2],[c3,c4]] 

     return x     
     #Above doesn't work. Returning string/datetime instead of x works fine.     

    def _run(self): 
     print 'Reached inside run..' 
     print 'main process id ..', os.getpid() 
     pool = Pool(processes=6) 
     names = ['frank', 'justin', 'osi', 'thomas', 'jim', 'rock', 'stonecold', 'machoman']   
     result = pool.map(unwrap_self_f, zip([self]*len(names), names), 1)   
     print type(result) 
     print result 


    def hello(self): 
     print 'Running hello....' 
     self._run() 

def test(): 
    logger.info('Starting....test') 
    c = C(1, 2) 
    print 'Running test....' 
    c.hello()  

def unwrap_self_f(arg, **kwarg): 
    print 'inside unwrap_self_f' 
    return C.f(*arg, **kwarg)  

if __name__ == '__main__': 
    print 'Loading multiprocessing...' 
    logger = multiprocessing.log_to_stderr() 
    logger.setLevel(logging.DEBUG) 
    test() 

我使用Python 2.6.6。 OS是windows-32bit/64位。

+0

你不是返回類,你回電話,以一個實例方法的類中:'返回CF(*阿根廷,** kwarg)' – 2014-12-03 09:51:17

回答

0

pool.map返回iterable不具有wait方法。

result = pool.map(unwrap_self_f, zip([self]*len(names), names), 1) 
    result.wait() # <--- no such thing 

沒有必要等待,因爲「它阻塞,直到結果準備就緒。」。

+0

你是對的here..the wait()方法不應該一直在那裏..我也試圖使用map_async(),它是從那裏剩下的。 – LearnToLive 2014-12-03 13:22:57

+0

那麼你最終使用了什麼?沒有「等待」的代碼正在爲我工​​作......如果這是您的問題的答案,請接受它。如果沒有 - 改變問題或解釋什麼是錯的。 – 2014-12-03 13:41:20

+0

代碼(沒有wait())可以正常工作。但是在f()中,我返回一個字符串。如果我嘗試返回自定義對象列表的列表..它不工作..程序永遠不會返回..看到更新的f()。這正是我想要實現的。再次感謝你的幫助。 – LearnToLive 2014-12-03 15:35:45