__main__上的Python全局变量

u5i3ibmn  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(160)

由于多处理需要放在windows中的__main__中,我发现我的全局变量没有传递给我的函数。

from multiprocessing import Pool, Value

def Proses(lines):
    global xyz
    try:
        print(lines)
        print(xyz)
    except Exception as e:
        print(e)

def counter_handler(args):
    global counter
    counter = args

def Dosomething():
    a = [i for i in range(10)]
    return a

if __name__ == '__main__':
    # i want to share xyz variable
    xyz = Dosomething()

    threads = []
    data = ["bjir", "bjir", "bjir"]
    counter = Value('i', 0)
    with Pool(1) as pool:
        p = Pool(1, initializer=counter_handler, initargs=(counter,))
        i = p.map_async(Proses, data, chunksize=1)
        i.wait()

我已经找了几个小时了,但还是没有线索,我想这可能是一个重复的问题,我知道,但我仍然找不到任何答案。有什么方法可以将xyz变量传递给函数吗?

i86rm4rw

i86rm4rw1#

正如您在示例中所写的,Poolinitializer=initargs=参数,您也可以使用它们来初始化全局变量:

from multiprocessing import Pool, Value

def Proses(lines):
    global xyz

    print(lines)
    print(xyz)

def Dosomething():
    a = [i for i in range(10)]
    return a

def init_pool(a, cnt):
    global xyz, counter
    xyz = a
    counter = cnt

if __name__ == "__main__":
    # i want to share xyz variable
    xyz = Dosomething()

    data = ["bjir", "bjir", "bjir"]
    counter = Value("i", 0)

    with Pool(1, initializer=init_pool, initargs=(xyz, counter)) as pool:
        i = pool.map_async(Proses, data, chunksize=1)
        i.wait()

图纸:

bjir
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
bjir
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
bjir
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

相关问题