Reputation: 1203
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)
Upvotes: 2
Views: 97
Reputation: 310147
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)
Upvotes: 6