How can I parallelize a function that modifies an attribute of a class? In the following example, change_arr()
modifies the contents of the attribute x
of the class based on loc
; it assigns -99
to each element of x
that equals loc
. When I run this script as written, I get the same array in both prints (and hence no modification took place). If I, however, comment the line using Pool
and uncomment the two lines that do the same job using a for loop I get [-3, -2, -1, 0, 1, 2, 3]
and [-99, 2, -99, 0, -99, 2, -99]
, which is what I want.
My question is, then, how can I parallelize the use of the function change_arr
to modify the same class attribute in parallel?
I am aware that there probably are better ways to implement this. However, the example is not exactly my code (as it is way longer and more complex), but a minimal example.
import numpy as np
from multiprocessing import Pool
class MyClass:
def __init__(self) -> None:
self.x = np.array([-3, -2, -1, 0, 1, 2, 3])
def process(self):
Pool(2).map(self.change_arr, [-3, -1, 1, 3])
# for i in [-3, -1, 1, 3]:
# self.change_arr(i)
def change_arr(self, loc):
self.x[self.x == loc] = -99
if __name__ == '__main__':
mc = MyClass()
print(mc.x)
mc.process()
print(mc.x)