简体   繁体   English

python中的池(多处理)内未访问全局变量

[英]Global variable not accessed inside pool(multiprocessing) in python

The global variable defined in main is accessed inside normal function but its not accessed in Pool() main 中定义的全局变量在普通函数中访问,但在 Pool() 中未访问

from multiprocessing import Pool    
import functools


def inc(x):
    print( x + 1)
    
    print(headers) # GETTING ERROR HERE

def dec(x):
    print (x - 1)
    

def add(x, y):
    print (x + y)
    
    
    
def a(f):
    f()
    


def main():
    print(headers)
    
    f_inc = functools.partial(inc, 4)
    f_dec = functools.partial(dec, 2)
    f_add = functools.partial(add, 3, 4)

    
    with Pool() as pool:
        res = pool.map(a, [f_inc, f_dec, f_add])

    print(res)


if __name__ == '__main__':
    global headers
    headers = {'Accept': 'application/json'}
    main()

Expected output is预期输出是

{'Accept': 'application/json'}
5
{'Accept': 'application/json'}
1
7
None

But the output i get is但我得到的输出是

{'Accept': 'application/json'}
    5

NameError: name 'headers' is not defined

The global variable is not getting accessed inside pool in multiprocessing.在多处理池中未访问全局变量。

You can't access it in separate pool processes because each process has started its own Python interpreter, and the global variable isn't in it.您无法在单独的池进程中访问它,因为每个进程都启动了自己的 Python 解释器,并且全局变量不在其中。

You need to pass the variables you need to each pool process.您需要将所需的变量传递给每个池进程。 There are a number of ways to communicate between Processes . Processes之间有多种通信方式。 One of them is a multiprocessing.Queue() , and there are other ways too.其中之一是multiprocessing.Queue() ,还有其他方法。 There are many examples in the Python.org docs that show how to do this here . Python.org 文档中有许多示例展示了如何在此处执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM