@senderleのここに加えて、一部のユーザーはの機能の使用方法についても疑問に思うかもしれませんmultiprocessing.Pool
。
良い点は、トップレベルの使い慣れたすべてのAPIを模倣する.Pool()
メソッドがmanager
インスタンスにあることですmultiprocessing
。
from itertools import repeat
import multiprocessing as mp
import os
import pprint
def f(d: dict) -> None:
pid = os.getpid()
d[pid] = "Hi, I was written by process %d" % pid
if __name__ == '__main__':
with mp.Manager() as manager:
d = manager.dict()
with manager.Pool() as pool:
pool.map(f, repeat(d, 10))
# `d` is a DictProxy object that can be converted to dict
pprint.pprint(dict(d))
出力:
$ python3 mul.py
{22562: 'Hi, I was written by process 22562',
22563: 'Hi, I was written by process 22563',
22564: 'Hi, I was written by process 22564',
22565: 'Hi, I was written by process 22565',
22566: 'Hi, I was written by process 22566',
22567: 'Hi, I was written by process 22567',
22568: 'Hi, I was written by process 22568',
22569: 'Hi, I was written by process 22569',
22570: 'Hi, I was written by process 22570',
22571: 'Hi, I was written by process 22571'}
これは、各プロセスがそのプロセスIDをグローバルDictProxy
オブジェクトに記録するわずかに異なる例d
です。