Yura YuLife

ITエンジニアの覚え書き。

python の multiprocecssing.Pool.map で複数の引数を持つ関数を扱う

python の multiprocessing を用いてマルチスレッド処理を行う際に、複数の引数を持つ関数を扱うときの Tips です。

動作環境

方法

やり方は簡単で、目的となる関数をラップするだけです。

# -*- coding: utf-8 -*-

from multiprocessing import Pool


def calc(a, b, c):
    result = a + b * c
    print("%d + %d * %d = %d" % (a, b, c, result))
    return result


def wrap_calc(num):
    return calc(*num)


def main():
    pool = Pool(processes=4)
    args = [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
    print("result = %s" % pool.map(wrap_calc, args))


if __name__ == '__main__':
    main()

結果

$ python pool.py 
1 + 2 * 3 = 7
2 + 3 * 4 = 14
4 + 5 * 6 = 34
3 + 4 * 5 = 23
result = [7, 14, 23, 34]

上記のように、wrap_calc メソッドにリスト型で引数を渡し calc メソッドに展開してあげれば解決します。

参考URL