- Published on
pythonのmultiproccessingで戻り値を使いたいとき
- Authors
- Name
- Kikusan
共有変数を使うとうまくできる。
import multiprocessing
def worker(procnum, return_dict):
'''worker function'''
print(str(procnum) + ' represent!')
return_dict[procnum] = procnum
if __name__== '__main__':
manager = multiprocessing.Manager()
return_dict = manager.dict()
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,return_dict))
jobs.append(p)
p.start()
for proc in jobs:
proc.join()
print(return_dict.values())
#0 represent!
#1 represent!
#2 represent!
#3 represent!
#4 represent!
#[0, 1, 2, 3, 4]
なお、pythonの並列処理はif __name__== '_main_':のなかで動かさないと
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce
an executable.
というエラーになる。