使用多处理池更改生成进程中主进程中的全局变量

Changing global variable in main process within a spawned process using multiprocessing Pool

我的示例代码如下:

from multiprocessing import Pool
GLOBAL_VAR = 0

def try_change_global_var(notused):
    global GLOBAL_VAR
    print(f"My own GLOBAL_VAR in current process starts as: {GLOBAL_VAR}")
    GLOBAL_VAR = 1
    print("I tried to change GLOBAL_VAR to 1")
    return "change"


if __name__ == '__main__':
    p1 = Pool(4)
    result = p1.map(try_change_global_var, range(4))
    print(result)
    print(f"GLOBAL_VAR in main process is still: {GLOBAL_VAR}")
    p1.close()

我读到每个生成的 Python 进程都有自己的全局变量,但是如果您看一下我的控制台输出,似乎所有 4 个生成的进程都在访问同一个变量,因为它是立即从 0 变为 1 并保持为 1。当 4 个进程完成时,来自 main 的全局变量当然仍然是 0.

My own GLOBAL_VAR in current process starts as: 0
I tried to change GLOBAL_VAR to 1
My own GLOBAL_VAR in current process starts as: 1
I tried to change GLOBAL_VAR to 1
My own GLOBAL_VAR in current process starts as: 1
I tried to change GLOBAL_VAR to 1
My own GLOBAL_VAR in current process starts as: 1
I tried to change GLOBAL_VAR to 1
['change', 'change', 'change', 'change']
GLOBAL_VAR in main process is still: 0

我可以根据被调用函数的 returns 列表在 main 中更改它,但这不是我想要的。我想从派生进程共享内存并更改主进程中的全局变量。

我无法通过 multiprocessing.Value 获得可用的玩具示例,希望能得到一些帮助。我发现的示例没有使用 Pool,并且能够将多个参数传递给它们在并行进程中 运行 的函数。

OS: Windows 10 Python3.9.5

这完全符合预期。当您生成一个进程时,您正在复制当前环境,并将其提供给新进程。该进程所做的更改发生在该进程中,并且仅发生在该进程中。

所以每个进程都将它自己的 GLOBAL_VAR更改为1,但该值完全独立于主进程中的GLOBAL_VAR。 Python 如果您需要跨多个线程使用一个变量,则提供“共享变量”,但它们有些昂贵。 (multiprocessing.Value)