Вот пример кода:
from multiprocessing import Pool
from time import sleep
def f(x):
print(x)
sleep(0.1)
return x * x
if __name__ == '__main__':
with Pool(2) as pool:
print(pool.map(f, range(100)))
Который распечатывает:
0
13
1
14
2
15
3
16
4
...
Если мы посмотрим на соответствующий исходный код в multiprocessing
:
def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
error_callback=None):
'''
Helper function to implement map, starmap and their async counterparts.
'''
self._check_running()
if not hasattr(iterable, '__len__'):
iterable = list(iterable)
if chunksize is None:
chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
if extra:
chunksize += 1
if len(iterable) == 0:
chunksize = 0
task_batches = Pool._get_tasks(func, iterable, chunksize)
Здесь мы имеем len(iterable) == 100
, len(self._pool) * 4 == 8
, поэтому chunksize, extra = 12, 4
, что приводит к chunksize = 13
, следовательно, вывод показывает, что задачи разбиты на пакеты по 13.