Reputation: 1070
I am trying to figure out how to properly modify a list in multiprocessing using Python. I have written a toy code:
input_list = ["A", "B", "C", "D", "E", "F"]
manager = Manager()
shared_list = manager.list()
shared_list = input_list[:]
def do_stuff(element, i):
global shared_list
shared_list[i] = element[i] * 2
print(shared_list[i])
processes = []
for i in range(len(input_list)):
p = Process(target=do_stuff, args=(input_list, i))
p.start()
processes.append(p)
for p in processes:
p.join()
print(shared_list)
I had created a shared list by means of Manager
and subsequently I tried to utilize it inside the do_stuff
function. The problem is that once the multiprocessing is over, shared_list
is not modify. Could you please help me to understand what I am doing wrong?
Upvotes: 0
Views: 149
Reputation: 312323
Your problem is here:
shared_list = input_list[:]
With this statement, you are replacing the value of shared_list
with the value of input_list[:]
(that is, you are discarding your manager.list
instance).
You're probably looking for:
shared_list[:] = input_list[:]
By using a slice assignment like this, you are setting the contents of shared_list
to the contents of input_list
. This is called "slice assignment" and there are a variety of tutorials out there that discuss it in more detail.
Upvotes: 3