4

I'm going to increase start global variable in the multi-process python,

Source :

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()

Output:

1
1
1

I use lock for start counter but it doesn't work, I was expecting to see this output:

1 # ==> start = 1
2 # ==> start = start + 1 = 2
3 # ==> start = start + 1 = 3
norok2
  • 25,683
  • 4
  • 73
  • 99
  • 1
    Possible duplicate of [Python multiprocessing global variable updates not returned to parent](https://stackoverflow.com/questions/11055303/python-multiprocessing-global-variable-updates-not-returned-to-parent) – a_guest Sep 26 '18 at 12:20

1 Answers1

3

You need to explicitly share the memory to make it work properly:

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)

Note the multiprocessing Value wrapper comes with its own lock.

kabanus
  • 24,623
  • 6
  • 41
  • 74