0
1

More than 3 years have passed since last update.

【Python】マルチプロセス(multiprocessing)時の値の受け渡し

Posted at

Pythonマルチプロセス間で変数を受け渡しするときに値が渡せなかったのでメモを残す

実装

4つの関数(f1,f2,f3,f4)を定義し、各関数を別プロセスで実行する。各関数では値の追加(append)を行い、最後メインプロセスから追加された値を確認する。

NG

変数を格納するために定義したtestlistは、メインプロセスにのみ存在するメモリ空間のため, 別プロセスからは参照更新が不可能な様子

  • プログラム
from multiprocessing import Process
from multiprocessing import Manager

testlist=[]
def f1():
    #print("function f1")
    testlist.append("f1")

def f2():
    #print("function f2")
    testlist.append("f2")

def f3():
    #print("function f3")
    testlist.append("f3")

def f4():
    #print("function f4")
    testlist.append("f4")

if __name__ == '__main__':
    for i in (0,1,2):
        p1 = Process(target=f1, args=())
        p1.start()
        p2 = Process(target=f2, args=())
        p2.start()
        p3 = Process(target=f3, args=())
        p3.start()
        p4 = Process(target=f4, args=())
        p4.start()

        p1.join()
        p2.join()
        p3.join()
        p4.join()
        p1.terminate()
        p2.terminate()
        p3.terminate()
        p4.terminate()
    print("")
    print("result: ",testlist)
  • 結果
result:  []

OK

Managerを使用して、変数を受け渡す。listを引数に設定しプロセス間でデータを受け渡す。 これによって各関数より値を更新したうえで、メインプロセスから確認することが可能。

  • プログラム
from multiprocessing import Process
from multiprocessing import Manager

def f1(dummy,testlist,num):
    #print("function f1")
    testlist.append("f1")

def f2(dummy,testlist,num):
    #print("function f2")
    testlist.append("f2")

def f3(dummy,testlist,num):
    #print("function f3")
    testlist.append("f3")

def f4(dummy,testlist,num):
    #print("function f4")
    testlist.append("f4")


if __name__ == '__main__':

    alllist=[]
    with Manager() as manager:
        for i in (0,1,2):
            d=manager.dict()
            l=manager.list([])
            p1 = Process(target=f1, args=(d,l,4*i+0))
            p1.start()
            p2 = Process(target=f2, args=(d,l,4*i+1))
            p2.start()
            p3 = Process(target=f3, args=(d,l,4*i+2))
            p3.start()
            p4 = Process(target=f4, args=(d,l,4*i+3))
            p4.start()


            p1.join()
            p2.join()
            p3.join()
            p4.join()
            p1.terminate()
            p2.terminate()
            p3.terminate()
            p4.terminate()
            alllist.extend(l)
    print("")
    print("result: ",alllist)
  • 結果
result:  ['f1', 'f2', 'f3', 'f4', 'f1', 'f2', 'f3', 'f4', 'f1', 'f2', 'f3', 'f4']
0
1
0

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
0
1