简体   繁体   English

Python多处理:跨进程共享变量的值递增

[英]Python multprocessing: Increment values of shared variables across processes

Here's a minimal example of what I want to achieve. 这是我要实现的最小示例。

The global INIT_* values should be incremented by each process and made available for another function ( print_locked in this example): 全局INIT_*值应由每个进程递增,并可供其他功能使用(在此示例中为print_locked ):

import multiprocessing as mp

INIT_NODE = mp.Value('i', 1000)
INIT_WAY = mp.Value('i', 1000)
INIT_REL = mp.Value('i', 1000)


def print_locked(a, b, c):
    print(a.value, b.value, c.value)


def process_results(a):
    with mp.Lock():
        INIT_NODE.value += 20000000
        INIT_WAY.value += 10000000
        INIT_REL.value += 1000000

    print_locked(INIT_NODE, INIT_WAY, INIT_REL)


def main():
    """Entry point for the program."""

    a = range(5)
    pool = mp.Pool(4)
    pool.map(process_results, a)


if __name__ == '__main__':
    main()

However, it seems that each process increments its own version of the initial values, which is exactly what I want to avoid. 但是,似乎每个进程都会增加其自己的初始值版本,这正是我要避免的事情。

Example output: 输出示例:

20001000 20001000 2001000
20001000 20001000 2001000
40001000 30001000 3001000
60001000 40001000 4001000
80001000 50001000 5001000

mp.Lock() create lock object but it does not lock the block of code. mp.Lock()创建锁定对象,但不会锁定代码块。 To lock critical region of code you should first call acquire method of mp.Lock object and call release method of the object after the critical region. 要锁定代码的关键区域,您应该首先调用mp.Lock对象的获取方法,然后在关键区域之后调用对象的释放方法。



INIT_NODE = mp.Value('i', 1000)
INIT_WAY = mp.Value('i', 1000)
INIT_REL = mp.Value('i', 1000)
lock = mp.Lock()


def process_results(a):
    lock.acquire()

    INIT_NODE.value += 20000000
    INIT_WAY.value += 10000000
    INIT_REL.value += 1000000
    print_locked(INIT_NODE, INIT_WAY, INIT_REL)
    lock.release()



Now the output of this program is the same for all run 现在,该程序的输出对于所有运行都是相同的

20001000 10001000 1001000
40001000 20001000 2001000
60001000 30001000 3001000
80001000 40001000 4001000
100001000 50001000 5001000

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

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