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)
asked Jun 11, 2013 at 12:26
user2435611
1,2031 gold badge13 silver badges19 bronze badges
1 Answer 1
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)
answered Jun 11, 2013 at 12:27
mgilson
312k70 gold badges658 silver badges723 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py