multiprocessing.Pool示例

时间:2010-12-10 22:21:33

标签: python multiprocessing

我正在尝试学习如何使用multiprocessing,并找到the following example

我想按如下方式对值进行求和:

from multiprocessing import Pool
from time import time

N = 10
K = 50
w = 0

def CostlyFunction(z):
    r = 0
    for k in xrange(1, K+2):
        r += z ** (1 / k**1.5)
    print r
    w += r
    return r

currtime = time()

po = Pool()

for i in xrange(N):
    po.apply_async(CostlyFunction,(i,))
po.close()
po.join()

print w
print '2: parallel: time elapsed:', time() - currtime

我无法得到所有r值的总和。

2 个答案:

答案 0 :(得分:19)

如果你打算像那样使用apply_async,那么你必须使用某种共享内存。此外,您需要放置启动多处理的部分,以便仅在初始脚本调用时完成,而不是通过池化进程调用。这是用地图做的一种方法。

from multiprocessing import Pool
from time import time

K = 50
def CostlyFunction((z,)):
    r = 0
    for k in xrange(1, K+2):
        r += z ** (1 / k**1.5)
    return r

if __name__ == "__main__":
    currtime = time()
    N = 10
    po = Pool()
    res = po.map_async(CostlyFunction,((i,) for i in xrange(N)))
    w = sum(res.get())
    print w
    print '2: parallel: time elapsed:', time() - currtime

答案 1 :(得分:6)

以下是我在python example documentation中找到的最简单的示例:

from multiprocessing import Pool

def  f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
    print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"

即使我能理解它也很简单 注意result.get()是触发计算的原因。