本文介紹了multiprocessing.Pool 示例的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我正在嘗試學習如何使用 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 示例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!