多处理。池examp

2024-06-03 05:27:27 发布

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

我正在学习如何使用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值的和。


Tags: theinfromimportfortimeexamplemultiprocessing
2条回答

如果要像那样使用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

下面是我在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()是触发计算的原因。

相关问题 更多 >