首页 > 解决方案 > Python多处理:不尊重chunksize参数,总是发送1个项目

问题描述

在这里阅读@Darkonaut 的答案后,我仍然无法将我的可迭代批次发送到函数进行多处理。

我的设置:

$ python --version
Python 3.6.7 :: Anaconda, Inc.
OS X 10.15.7
Also tested on RHEL 8, same result.

这是一个带有以下输出的最小示例

import multiprocessing
from itertools import repeat

iterable = list(range(1000))

def dummy_func(arg1, arg2):
    if hasattr( arg1, "__len__"):
        print(f"Batch size: {len(arg1)}")
    else:
        print("Single item sent to func.")

    print(f"Arg1: {arg1}, Arg2: {arg2}")

with multiprocessing.Pool(processes=8) as pool:
    pool.starmap(
        dummy_func, 
        zip(
            iterable, 
            repeat("Static second variable")),
        chunksize = 10)
    pool.close()
    pool.join()

无论 chunksize 是 None 还是大于 1 的任何数字,它都会发送单个项目。输出:

Single item sent to func.
Arg1: 0, Arg2: Static second variable
Single item sent to func.
Arg1: 1, Arg2: Static second variable
Single item sent to func.
Arg1: 2, Arg2: Static second variable
...
Arg1: 989, Arg2: Static second variable

我的期望是 arg1 将是长度为块大小的项目列表,这不正确吗?

标签: pythonmultiprocessingpython-multiprocessing

解决方案


推荐阅读