
import pprocessimport timenumbers=[0,0]# find system time and store in global variabledef find_time(index): global numbers x=time.time() print "Setting element %s of numbers to %f" % (index,x) numbers[index]=x return x# parallel execution of the functionresults=pprocess.pmap(find_time,[0,1,2,3,4,5,6,7,8,9],limit=6)for y in results: print '%f' % y# this List is unchangedprint numbers# serial execution of the functionfor x in [0,9]: find_time(x)# Now it seems to workprint numbers
“numbers”只是一个零列表,为了演示,我试图将每个列表元素设置为当前系统时间.当使用pprocess调用时,这不起作用,但是当我使用一个简单的for循环来调用该函数时,全局变量就会改变.
我花了一些时间阅读全球变量,并真诚地希望这不是一个微不足道的问题.任何人都可以向我解释发生了什么事吗?
非常感谢,
恩诺
解决方法 我的理解是pprocess使用了底层处理.如果是这种情况,那么每次运行该函数时,它实际上都是一个单独的过程.因此,当函数返回时,这些更改不会显示.您可能需要将列表设为multiprocessing.Manager.
例如
numbers = multiprocessing.Manager().List([0]*10)总结
以上是内存溢出为你收集整理的Python:如何使用pprocess修改函数中的全局变量全部内容,希望文章能够帮你解决Python:如何使用pprocess修改函数中的全局变量所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)