2

I'm trying to do a task where I would assign something to a list. I'll do it with multiprocessing. After all task is finish, I want to sum all of it. But, What I get is not what i expected. Do you know why do this happen? Below is just a sample code. The result should be 45, instead of 0.

from multiprocessing import Process

def a(b):
    for i in range(10):
        b[i] = i

b = [0 for _ in range(10)]

p = Process(target=a, args=(b,))
p.start()
p.join()

print sum(b)

1 Answer 1

6

The reason is because the list b is mutated in a separate process. When the process gets joined, the original process knows nothing about the mutations to b. The way to fix this is to have your list managed by a multiprocessing.Manager.

from multiprocessing import Process,Manager

def a(b):
    for i in range(10):
        b[i] = i

b = [0 for _ in range(10)]

#create a manager to manage access to `b`
manager = Manager()
b = manager.list(b)

p = Process(target=a, args=(b,))
p.start()
p.join()

print sum(b)
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.