You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用multiprocessing Pool如何向函数传递任意数量二维数组

并行读取文件时使用partial和pool.map传递可变参数的问题

问题代码中的错误分析

  1. partial调用时使用*args=*terse_args属于无效语法,partial不支持这种展开参数的写法。
  2. 位置参数传递时出现multiple values for 'name'错误,是因为pool.map会自动将迭代对象的每个元素作为第一个参数传给目标函数,若partial绑定参数的顺序不对,会导致参数冲突。
  3. read_profiles函数内的for g in len(args)是错误写法,会触发TypeError: 'int' object is not iterable,需改为for g in range(len(args))。

修正后的代码

import numpy as np
from multiprocessing import Pool
from functools import partial

def read_profiles(stamp, name, cols, *args):
    # 读取单个文件的函数
    filename = name + '-' + str(int(timestep[stamp])) + '.dat'
    with open(filename) as f:
        xloc = 0
        for line in f:
            ele = line.rstrip("\n").split()
            # 修正循环迭代逻辑
            for g in range(len(args)):
                args[g][stamp, xloc] = float(ele[cols[g]])
            xloc += 1

timestep = np.arange(1, 51)
# 初始化存储数组
x = np.ndarray(shape=(len(timestep), 1001))
Ex = np.ndarray(shape=(len(timestep), 1001))
j1 = np.ndarray(shape=(len(timestep), 1001))
j2 = np.ndarray(shape=(len(timestep), 1001))
j3 = np.ndarray(shape=(len(timestep), 1001))
j4 = np.ndarray(shape=(len(timestep), 1001))

terse_args = [x, Ex]
curr_args = [j1, j2, j3, j4]

with Pool(4) as pool:
    # 用partial绑定name、cols和可变数组参数,stamp由pool.map自动传入
    pool.map(partial(read_profiles, name='terse', cols=[0, 2], *terse_args), range(len(timestep)))
    pool.map(partial(read_profiles, name='current', cols=[1, 2, 3, 4], *curr_args), range(len(timestep)))

关键修正说明

  • partial参数绑定:将name、cols以及可变数组参数直接作为位置参数传给partial,*terse_args会把列表元素展开为partial的位置参数,确保pool.map传入的stamp作为函数第一个参数,避免参数冲突。
  • 多进程数组写入注意:当前代码中numpy数组会被复制到子进程,子进程的修改不会同步到主进程数组。若需要共享内存写入,建议使用multiprocessing.Array结合numpy包装,或sharedmem第三方库。

内容的提问来源于stack exchange,提问作者Saurabh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 16:58:16