因为在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变量传递给我的函数?

推荐答案

正如您在示例中所写的,Pool具有initializer=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]

Python相关问答推荐

Plotly Dash函数来切换图形参数-pPython

在Python中使用一行try

在Transformer中使用LabelEncoding的ML模型管道

创建带有二维码的Flask应用程序,可重定向到特定端点

Matplotlib轮廓线值似乎不对劲

有什么方法可以避免使用许多if陈述

返回nxon矩阵的diag元素,而不使用for循环

使用新的类型语法正确注释ParamSecdecorator (3.12)

仿制药的类型铸造

Python 约束无法解决n皇后之谜

按顺序合并2个词典列表

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

我如何根据前一个连续数字改变一串数字?

Pandas DataFrame中行之间的差异

迭代嵌套字典的值

根据列值添加时区

索引到 torch 张量,沿轴具有可变长度索引

Geopandas未返回正确的缓冲区(单位:米)

numpy.unique如何消除重复列?

Pandas:计算中间时间条目的总时间增量