Python:如何使用pprocess修改函数中的全局变量
发布时间:2020-12-20 13:30:18 所属栏目:Python 来源:网络整理
导读:当使用从pprocess调用的函数时,我似乎无法在 Python中修改全局变量.这是我的例子: import pprocessimport timenumbers=[0,0]# find system time and store in global variabledef find_time(index): global numbers x=time.time() print "Setting element %
当使用从pprocess调用的函数时,我似乎无法在
Python中修改全局变量.这是我的例子:
import pprocess import time numbers=[0,0] # find system time and store in global variable def 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 function results=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 unchanged print numbers # serial execution of the function for x in [0,9]: find_time(x) # now it seems to work print numbers “numbers”只是一个零列表,为了演示,我试图将每个列表元素设置为当前系统时间.当使用pprocess调用时,这不起作用,但是当我使用一个简单的for循环来调用该函数时,全局变量就会改变. 我花了一些时间阅读全球变量,并真诚地希望这不是一个微不足道的问题.任何人都可以向我解释发生了什么事吗? 非常感谢, 恩诺 解决方法
我的理解是pprocess使用了底层处理.如果是这种情况,那么每次运行该函数时,它实际上都是一个单独的过程.因此,当函数返回时,这些更改不会显示.
您可能需要将列表设为 例如 numbers = multiprocessing.Manager().list([0]*10) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |