2011-06-22 16 views
2

map_asyncで面白い問題があります。わかりません。map_async()に文字列のリストを渡す

私はプロセスプールを持つpythonのマルチプロセッシングライブラリを使用しています。

from multiprocessing import Pool, cpu_count 
import functools 

dictionary = /a/file/on/my/disk 
passin = /another/file/on/my/disk 

num_proc = cpu_count() 

dictionary = readFiletoList(fdict) 
dictionary = sortByLength(dictionary) 

words = readFiletoList(passin, 'WINDOWS-1252') 
words = sortByLength(words) 

result = pool.map_async(functools.partial(mpmine, dictionary=dictionary), [words], 1000) 

def readFiletoList(fname, fencode='utf-8'): 
    linelist = list() 
    with open(fname, encoding=fencode) as f: 
    for line in f: 
     linelist.append(line.strip()) 
    return linelist 


def sortByLength(words): 
    '''Takes an ordered iterable and sorts it based on word length''' 
    return sorted(words, key=len) 

def mpmine(word, dictionary): 
    '''Takes a tuple of length 2 with it's arguments. 

    At least dictionary needs to be sorted by word length. If not, whacky results ensue. 
    ''' 
    results = dict() 
    for pw in word: 
    pwlen = len(pw) 
    pwres = list() 
    for word in dictionary: 
     if len(word) > pwlen: 
     break 
     if word in pw: 
     pwres.append(word) 
    if len(pwres) > 0: 
     results[pw] = pwres 
    return results 



if __name__ == '__main__': 
    main() 

は辞書と単語の両方がリストされている:私は今、私が持っている)

をと比較する文字列のリストを渡そうとmap_asyncを使用して関数(と比較する文字列のリストです弦のこれにより、設定した金額の代わりに、1つのプロセスのみが使用されます。変数 'words'から角括弧を取り除くと、順番に各文字列の文字を繰り返し処理するように見えます。

私は、1000文字列の単語を取り出し、ワーカープロセスに渡してから結果を得ることを望んでいます。これは、ばかばかしい並列処理のためです。

EDIT:より明確なことを行うためのコードを追加しました。

+0

もっと多くのコードを付けるべきでしょう。今のところ問題を再現するためには多くを追加する必要があります。 –

答えて

2

私は実際に自分自身を考え出しました。私は一緒に来て、同じ問題を抱えているかもしれない他の誰のためにもここに回答を投稿するつもりです。私が問題を抱えていた理由は、map_asyncがリスト(この場合は文字列)から1つの項目を取り出し、それを文字列のリストを期待していた関数に渡すためです。だから、それは基本的に各文字列を文字のリストとして扱っていました。 mpmineの修正コードは次のとおりです。

def mpmine(word, dictionary): 
    '''Takes a tuple of length 2 with it's arguments. 

    At least dictionary needs to be sorted by word length. If not, whacky results ensue. 
    ''' 
    results = dict() 
    pw = word 
    pwlen = len(pw) 
    pwres = list() 
    for word in dictionary: 
    if len(word) > pwlen: 
     break 
    if word in pw: 
     pwres.append(word) 
    if len(pwres) > 0: 
    results[pw] = pwres 
    return results 

これは他の誰かが同様の問題に直面するのを助けてくれることを願っています。

関連する問題