LoginSignup
28
24

More than 5 years have passed since last update.

pythonでmultiprocessingを使って並列処理をする時に引数を複数取る方法

Last updated at Posted at 2016-11-24

サンプルコード

sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from multiprocessing import Pool
from collections import Counter

# ここを並列処理する
def func(n, argument1, argument2):
    # 2倍して5を足す処理
    return n * argument1 + argument2

def wrapper(args):
    # argsは(i, 2, 5)となっている
    return func(*args)

def multi_process(sampleList):
    # プロセス数:8(8個のcpuで並列処理)
    p = Pool(8)
    output = p.map(wrapper, sampleList)
    # プロセスの終了
    p.close()
    return output

if __name__ == "__main__":
    # 100回の処理を並列処理で行う
    num = 100

    # (i, 2, 5)が引数になる
    sampleList = [(i, 2, 5) for i in range(num)]

    # sampleListの要素を2倍して5を足す
    output = multi_process(sampleList)

説明

pythonのバージョンは2.7.10です
コードを見ればわかると思いますが

  • multiprocessingを使って並列処理をする場合、listにして渡すのが簡単です。
  • wrapper()関数を間に挟むことで複数の引数を渡すことができます。
  • 今回のサンプルではリストの最初の要素を全て2倍して5を足すという処理を行っています。
  • プロセスの終了(Pool.close())を忘れてしまうとプロセスを開きすぎてToo many open filesというエラーが発生する可能性があります。
28
24
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
24