【问题标题】:How can I use this function in multiprocessing?如何在多处理中使用此功能?
【发布时间】:2019-07-20 19:54:29
【问题描述】:

我想在多处理中应用这个功能:

import multiprocessing
import numpy as np

a = np.random.randint(1,4, size=(10,10,10))

def function(input_field,[num1,num2,num3]):
    pass

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=4)
    test_list = [(a,[27.5, 27.5, 25]), (b,[27.5, 27.5, 25]), (c,[27.5, 27.5, 25]), (d,[27.5, 27.5, 25])]
    results = pool.map(function, test_list)
    pool.close()
    pool.join()    

如何将function(input_field,[num1,num2,num3]) 应用于多处理?

【问题讨论】:

  • 这是function(input_field,[num1,num2,num3]) 语法错误。只需将函数更改为接收 1 个参数,即列表中的元组,然后将其解压缩到函数中或将 map 更改为 starmap
  • 列表[27.5, 27.5, 25] 对所有项目都相同,这是故意的吗?
  • starmap 对我来说是一个简单的解决方案。 @RomanPerekhrest 是的,它是故意写的。
  • @Newbie0105,我没有告诉你星图

标签: python function multiprocessing python-multiprocessing


【解决方案1】:

根据 test_list 的结构,您有 2 个选项:

  1. 修改您的函数以支持单个参数并将其解压缩到函数中并继续使用map

    def function(arg):
        input_field, l = arg
    
  2. 使用starmap 并修复你的函数定义,因为test_list 的结构是starmap 期望得到的:

    def function(input_field, l):
    ...
    results = pool.starmap(function, test_list)
    

【讨论】:

  • 我的意思是,您对我的代码的评论有效。我刚刚从“地图”更改为“星图”,它工作了。非常感谢!
猜你喜欢
  • 2019-06-20
  • 2012-01-25
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2021-01-17
  • 1970-01-01
  • 2018-01-11
相关资源
最近更新 更多