如何在不同的进程python中增加计数器?

时间:2018-09-26 12:03:26

标签: python python-2.7 multiprocessing

我将在多进程python中增加start全局变量

来源:

from multiprocessing import Process, Lock

start = 0

def printer(item, lock):
    """
    Prints out the item that was passed in
    """
    global start
    lock.acquire()
    try:
        start = start + 1
        print(start)
    finally:
        lock.release()

if __name__ == '__main__':
    lock = Lock()
    items = ['tango', 'foxtrot', 10]
    for item in items:
        p = Process(target=printer, args=(item, lock))
        p.start()

输出:

1
1
1

我为start计数器使用了锁,但是它不起作用, 我期待看到此输出:

1 # ==> start = 1
2 # ==> start = start + 1 = 2
3 # ==> start = start + 1 = 3

1 个答案:

答案 0 :(得分:3)

您需要explicitly share the memory才能使其正常工作:

from multiprocessing import Process, Lock, Value

start = Value('I',0)

def printer(item):
    """
     Prints out the item that was passed in
    """
    with start.get_lock():
        start.value+=1
        print(start.value)

请注意,多处理Value包装器具有自己的锁。