我试图使用Python多处理库,但是在全局定义变量时遇到问题。因为某些原因,我得到了错误“名称错误:全局名称。。。is not defined“原始程序非常复杂,因此我在下面的代码中重现了我的问题:
import multiprocessing
import time
import timeit
def setGlobal():
global globalVar
globalVar = 2
def mp_worker(arguments):
# do some processing....
data = arguments[0]
# need to use global data
the_time = globalVar
time.sleep(int(the_time))
def f(processes = 3):
global pool
pool = multiprocessing.Pool(processes)
def mp_handler(number):
inputs = []
inputs.append([1])
inputs.append([2])
print("Begin multiprocessing test...for test "+str(number))
start_time = timeit.default_timer()
pool.map(mp_worker, inputs)
print("Time taken to calculate trades: %4.4f " %(timeit.default_timer() - start_time))
if __name__ == '__main__':
#define global variable
setGlobal()
# initialise pool
f(3)
# Get error: NameError: global name 'globalVar' is not defined
mp_handler(1)
现在我尝试的一个潜在解决方案是:
^{pr2}$然而,当我调用setGlobal(1)时,它对mp_worker没有影响?当我需要全局定义的值为1时,它是4。为什么会这样?这个问题可以克服吗?在
global
语句不使变量成为全局变量,而是使变量在函数范围内可访问。在只需在顶层设置变量(即在任何函数或类之外)就可以使其本质上是全局的。 因此,在任何函数和类之外设置该值,然后在需要在函数内更改时使用
global var_name
声明它。 请注意,您不需要使用global
命令来读取全局变量,只有当您需要在函数中更改它时。在请注意,全局变量在多处理进程之间并不能很好地发挥作用:我发现有必要使用几个多处理队列对象在进程之间发送值(遗憾的是)。在
相关问题 更多 >
编程相关推荐