在Python中并行运行2个以上不同的独立类方法

2024-09-28 05:38:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉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密集型的,每次调用时都返回不同的值。在

我有一台安装了Ubuntu和python2.6.5的8核cpu的机器(很遗憾,无法更新),另一台机器只有一个i7处理器和python2.7.5(也不能更新)。我也无法安装新的软件包。在

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

你能给我举几个例子吗?或者给我一些建议,告诉我如何做到这一点?谢谢


Tags: test程序机器returndefsomethingclassfunc
2条回答

好吧,这非常接近文档中的一个例子……但是我认为使用Pool比显式处理更容易,使用Futures比使用简单的池更容易。另外,^{}模块的文档比multiprocessing文档要简单得多。所以,让我们这样做:

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中就没有这个模块,所以您需要安装the backport。在


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

^{pr2}$

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

http://pymotw.com/2/multiprocessing/basics.html

他关于标准图书馆的书也值这个钱。在

相关问题 更多 >

    热门问题