运行2+;Python中并行的独立类方法

运行2+;Python中并行的独立类方法,python,python-2.7,multiprocessing,Python,Python 2.7,Multiprocessing,我不熟悉Python中的多处理。我有一个简单的程序,如: class test: ... def func(): return something inst1 = test(init1, ...) inst2 = test(init2, ...) inst3 = test(init3, ...) x = [] while(some_condition): a = inst1.func() b = inst2.func() c = ins

我不熟悉Python中的多处理。我有一个简单的程序,如:

class test:
    ...
    def func():
        return something

inst1 = test(init1, ...)
inst2 = test(init2, ...)
inst3 = test(init3, ...)

x = []
while(some_condition):
    a = inst1.func()
    b = inst2.func()
    c = inst3.func()
    x.append(do_something(a, b, c))
func是CPU密集型的,每次调用时都返回不同的值

我有一台装有2个8核CPU的机器,安装了Ubuntu和Python 2.6.5(不幸的是,无法更新),另一台机器只有一个i7处理器和Python 2.7.5(也无法更新)。我也无法安装新的软件包

我相信如果三种方法同时运行(理论上操作系统应该将它们分配到不同的内核),我可以获得一些性能,但我不确定如何继续。对于多处理来说,文档充其量是晦涩难懂的

你能给我举几个例子或者给我一些建议吗?谢谢

Doug Hellmans的“每周模块”经常有很好的例子:


他写的关于标准库的书也是值得的。

好吧,这与文档中的一个例子非常接近……但我认为使用
池比使用显式流程更容易,使用
期货比使用简单池更容易。此外,模块的文档比
多处理
文档更简单。那么,让我们这样做:

x = []
with concurrent.futures.ProcessPoolExecutor(max_workers=3) as executor:
    while some_condition:
        a = executor.submit(func1)
        b = executor.submit(func2)
        c = executor.submit(func3)
        concurrent.futures.wait((a, b, c))
        x.append(do_something(a.result(), b.result(), c.result()))
如果您使用的是Python2.5-3.1,则stdlib中不会有此模块,因此需要安装


为了进行比较,下面是为每个函数使用显式
多处理.Process
时的情况:

def background(f):
    q = multiprocessing.Queue()
    def wrapped(q):
        q.put(f())
    p = multiprocess.Process(target=wrapped, args=q)
    p.start()
    return p, q

x = []
while some_condition:
    pa, qa = background(func1)
    pb, qb = background(func2)
    pc, qc = background(func3)
    pa.join()
    pb.join()
    pc.join()
    x.append(do_something(qa.get(), qb.get(), qc.get())

您的解决方案对函数适用,但我是指方法,对不起。@user2329994:同样的基本方法也适用于方法。像
inst.func
这样的绑定方法是一个可以像函数一样传递和调用的值。你可能会遇到酸洗的问题,但这些问题通常很容易解决,不管怎样,当你遇到问题时,你可以跨越这座桥。