簡體   English   中英

如何在Python 2.7中並行調用不同實例化的類方法?

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

我有一個包含執行計算的函數的類。 如果我有這些對象的多個實例,我如何使計算並行進行?

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

然后在另一個腳本中:

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

如何讓其中一個工作人員執行g1.compute()和另一個g2.compute()?

在python2.7上,你必須定義一個調用給定參數的compute方法的worker函數,然后你可以將它與pool.map()

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

在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