My question is related to parallelizing a python code and I want to know how we can run a function for different instances of a class to decrease the runtime.
What I have: I have multiple instances of a class A (stored in a list called instances). This class has a function add. Now, we have multiple independent tasks, one for each instance of class A where the input to all these tasks is one thing (number n in my example). Each instance needs to apply function add to n and return a number. We want to store the returned numbers of all instances in a list (list results in my example).
What I want: As you can see, in this example, the tasks can be parallelized as there is no need for one to wait for the other one to gets done. How can we parallelize the simple code below? Since nothing is shared between the different instances, I guess we can even use multithreading, right? Or the only way is to use multiprocessing?
class A(object):
def __init__(self, q):
self.p = q
def add(self, num):
return self.p + num
instances = []
for i in xrange(5):
instances.append(A(i))
n = 20
results = []
for inst in instances:
results.append(inst.add(n))
print(results)
Output: [20, 21, 22, 23, 24]