I have the following code:
import multiprocessing
manager = multiprocessing.Manager()
Function that appends list if it's length is less than 4 or creates a new one with initial value 'y'.
def f(my_array):
if len(my_array) < 4:
my_array.append('x')
else:
my_array = ['y']
print(my_array)
Initialization of list and creating processes.
if __name__ == '__main__':
my_array = manager.list(['a', 'b', 'c'])
p1 = Process(target=f, args=(my_array))
p2 = Process(target=f, args=(my_array))
p3 = Process(target=f, args=(my_array))
p4 = Process(target=f, args=(my_array))
p5 = Process(target=f, args=(my_array))
p1.start()
p2.start()
p3.start()
p4.start()
p5.start()
p1.join()
p2.join()
p3.join()
p4.join()
p5.join()
Output I got:
['a', 'b', 'c', 'x']
['y']
['y']
['y']
['y']
I don't understand why the list is appended only once. I expected that in the third output line I will observe list ['y'] appended by 'x', so ['y', 'x'], the fourth one ['y', 'x', 'x'] and so on. It seems like shared memory is leaky or does not permit to make a change by functions from multiple processes. What can I do to enable the targeted behavior?