使用 starmap() Python 创建对象 + 调用函数的多处理 [英] Multiprocessing for creating objects + calling functions using starmap() Python

查看:99
本文介绍了使用 starmap() Python 创建对象 + 调用函数的多处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建 Training 类的对象并创建多个调用 print() 函数的进程.

I would like to create objects of class Training and create multiple processes which call the print() function.

我有一个课程培训:

class Training():

    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2
    
    def print(self):
        print(self.param1)
        print(self.param2)

我尝试使用 starmap 函数以如下方式创建 5 个进程:

I have tried to use the starmap function to create 5 processes in the following way:

import multiprocessing as mp

num_devices = 5

func_args = []
for i in range (0, num_devices):
    func_args.append((i, i*10))

with mp.Pool(num_devices) as pool:
    obj = pool.starmap(Training, func_args, chunksize=1)
    obj[0].print()
    obj[1].print()
    obj[2].print()
    obj[3].print()
    obj[4].print()

然而,这段代码是创建多个进程来创建对象,而不是运行 print() 函数.我怎样才能以正确的方式做到这一点?

However, this code is is creating multiple processes to create the objects, and not to run the print() function. How can I do it in the correct way?

推荐答案

创建一个用所需参数初始化的对象列表,以及一个调用对象方法的辅助函数:

Create a list of objects initialised with the required parameters, and a helper function to call the method of object:

def helper_func(obj):
    obj.print()

func_args = []
for i in range (0, num_devices):
    obj = Training(i, i*10)
    func_args.append(obj)

with mp.Pool(num_devices) as pool:
    pool.map(helper_func, func_args, chunksize=1)

这篇关于使用 starmap() Python 创建对象 + 调用函数的多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆