multiprocessing.Pool example(multiprocessing.Pool 示例)
本文介绍了multiprocessing.Pool 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试学习如何使用 multiprocessing,结果发现 下面的例子.
I'm trying to learn how to use multiprocessing, and found 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 值的总和.
I can't get the sum of all r values.
推荐答案
如果你要像这样使用 apply_async,那么你必须使用某种共享内存.此外,您需要放置启动多处理的部分,以便它仅在由初始脚本调用时完成,而不是池进程.这是使用地图的一种方法.
If you're going to use apply_async like that, then you have to use some sort of shared memory. Also, you need to put the part that starts the multiprocessing so that it is only done when called by the initial script, not the pooled processes. Here's a way to do it with map.
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
这篇关于multiprocessing.Pool 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:multiprocessing.Pool 示例
![](/xwassets/images/pre.png)
![](/xwassets/images/next.png)
猜你喜欢
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01