В дополнение к @ senderle здесь, некоторые могут также задаться вопросом, как использовать функциональность multiprocessing.Pool
здесь.
Приятно то, что в экземпляре manager
есть метод .Pool()
который имитирует все знакомые API верхнего уровня `multiprocessing.
from itertools import repeat
import multiprocessing as mp
import os
import pprint
def f(d):
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'}
Это немного другой пример, где каждый процесс просто регистрирует свой идентификатор процессаглобальный DictProxy
объект d
.