简体   繁体   English

如何在Python 2.7中并行调用不同实例化的类方法?

[英]How to call class methods from different instantiations in parallel in Python 2.7?

I have a class which contains functions that perform calculations. 我有一个包含执行计算的函数的类。 If I have several instances of these objects, how do I make the calculations to go in parallel? 如果我有这些对象的多个实例,我如何使计算并行进行?

class SomeClass:
    def __init__(self, arg):
    ....
    def compute(self):
    ....

And then in a different script: 然后在另一个脚本中:

from multiprocessing import Pool
from wherever import SomeClass
    g1 = SomeClass(arg1)
    g2 = SomeClass(arg2)
    pool = Pool(processes = 2)

How do I make one of the workers do g1.compute() and the other g2.compute()? 如何让其中一个工作人员执行g1.compute()和另一个g2.compute()?

On python2.7 you'll have to define a worker function that calls the compute method on the given argument, then you can use it with pool.map() : 在python2.7上,你必须定义一个调用给定参数的compute方法的worker函数,然后你可以将它与pool.map()

def call_compute(o):
    return o.compute()
...
result = pool.map(call_compute, [g1, g2])

On python3 (tested on 3.5) it's possible to use pool.map(SomeClass.comute, [g1, g2]) instead because pickling instance methods is supported there. 在python3上(在3.5上测试),可以使用pool.map(SomeClass.comute, [g1, g2])因为那里支持pool.map(SomeClass.comute, [g1, g2])实例方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM