Lets say I have a myfunc that takes in an input i and j, calculates their sum and populates a passed-in array with the answer. This is what the problem looks like:
import numpy as np
from functools import partial
from multiprocessing import Pool
def myfunc(i: int, j: int, some_array: np.ndarray):
ans = i+j
some_array[i,j] = ans
some_array = np.zeros(shape = (2,2))
execute = partial(myfunc, some_array = some_array)
for i in range(2):
for j in range(2):
execute(i,j)
print(some_array)
[[0. 1.]
[1. 2.]]
Now, lets imagine I would like to parallelize this code. I do so in the following way:
iter = [(i,j) for i in range(2) for j in range(2)]
with Pool() as p:
p.starmap(execute, iterable = iter)
This doesn't update the empty array everytime execute is called with different args. The final array is all zeros. This may be because p.starmap yields a list of all results at the end but given that execute is called for each iterable it should execute some_array[i,j] = ans in every call.
Any ideas/ help is much appreciated.