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
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.