The first one should be:
import multiprocessing as mp
def func(list):
x = 5
list *= 5
print('list_in_sub: ', list)
if __name__ == "__main__":
list = mp.Manager().list(range(2))
p1 = mp.Process(target=func, args=( list,))
p1.start()
p1.join()
print('list_in_main: ', list)
# list_in_sub: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
# list_in_main: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
The second one should be:
import multiprocessing as mp
def func(list):
x = 5
list.append(x)
print('list_in_sub: ', list)
if __name__ == "__main__":
list = mp.Manager().list(range(2))
p1 = mp.Process(target=func, args=(list,))
p1.start()
p1.join()
print('list_in_main: ', list)
# list_in_sub: [0, 1, 5]
# list_in_main: [0, 1, 5]
Explanation:
- For the first one,
list = list*5
defines a new variable list
inside the function. Since this is different from the list
received, the contents are different. In contrast, list *= 5
updates the variable in place.
- The second one is a bug.
.append
method adds a new value to the list in place, and returns nothing. Hence, list = list.append(x)
adds x
to the original list, and defines a new variable list
as None inside the function.
- Note:
list
is a reserved keyword; you may want to use different variable names to avoid errors.
The example above may not be that interesting because the list is updated only by one process. The following demonstrates that two processes share and update the same list in a random order.
import multiprocessing as mp
def add_positive(lst):
for i in range(1, 31):
lst.append(i)
def add_negative(lst):
for i in range(1, 31):
lst.append(-i)
if __name__ == "__main__":
lst = mp.Manager().list([0])
p1 = mp.Process(target=add_positive, args=(lst,))
p2 = mp.Process(target=add_negative, args=(lst,))
p1.start()
p2.start()
p1.join()
p2.join()
print('Result: ', lst)
#Result (order should vary):
#[0, 1, 2, 3, 4, -1, 5, -2, 6, -3, 7, -4, -5, 8, -6, 9, -7, 10, -8,
#11, -9, 12, -10, 13, -11, -12, 14, -13, 15, -14, 16, -15, 17, -16,
#18, -17, 19, -18, 20, -19, 21, -20, -21, 22, -22, 23, -23, 24, -24,
#25, -25, 26, -26, 27, -27, 28, -28, 29, -29, 30, -30]