Python多进程类对象

0 投票
2 回答
844 浏览
提问于 2025-04-16 16:30

假设我有一个Python类:

class Something:
    def __init__(self, a, b, c):
        initialize_object_with_args()

    def run(self):
        do_something()

    def result(self):
        return result

现在我想创建这个类的多个对象(这些对象是独立的,彼此之间不需要交换数据),并在一台配有多核CPU的电脑上同时运行它们……每次运行时唯一不同的是输入参数(a, b, c)……

所以我需要这样的东西:

results = []
[PARALLEL START]
    obj = Something(a, b, c)
    obj.run()
    results.append(obj.results())
[PARALLEL END]

然后我就可以评估结果了!我了解到多进程模块可能是我需要的,但我不太清楚具体怎么用,也不知道它是否能满足我的需求,或者该怎么做?

快速补充:我需要用Python来实现……不想用外部模块……只用标准的Python安装……

2 个回答

0

你可以看看这个链接:http://wiki.python.org/moin/ParallelProcessing,特别是这里的内容:http://pypi.python.org/pypi/pprocess

这个小库正好能满足你的需求:http://honeypot.net/yet-another-python-map

0

这看起来和这个非常相似。

from multiprocessing import Pool

def func(*args):
    obj = Something(*args)
    obj.run()
    return obj.results()

pool = Pool()
results = pool.map(func, ((1,2,3), (4,5,6)))

撰写回答