I have a list of class instances. Each of this class objects have a method function that I want to run and I want to parallelize across the class instances since there's a lot of them. For example, I have this class object:
class Person(object):
def __init__(self, name):
self.name = name
def register(self):
self.registered = True
Now I defined a list of class instances of Person()
persons = [Person(i) for i in ["Bernard", "Enrik", "Joseph"]]
I want to parallelize the running of Person.register()
method function across the values in persons. Using multiprocessing.Pool, here's what I did. Since you can't pickle method function, I wrap it in another function.
import multiprocessing as mp
def reg(person):
person.register()
pool = mp.Pool(processes=mp.cpu_count()//2)
res = list(pool.map(reg, persons))
The code runs without error by the way, so now I am expecting that every Person instance in the list will have an attribute registered
set to True
but when I check each class instance, it doesn't contain attribute registered
. For example, checking if registered
is an attribute of persons[0],
hasattr(persons[0], "registered")
>>> False
Why is this so? How can I solve this?