MMM
MMM

Reputation: 383

Multiprocessing For Loop

I have a few CPUs at my disposal on a virtual machine. I have a rather simple for loop to compute, which I would like to multiprocess as it computes separate parts.

results = []
for i in range(n_iterations):
   result = compute_value(i)
   results.append(result)

The answers to this question consider the case where there is an data_inputs list that you want to iterate through. I tried to adapt it to my case, but it failed and I am just utterly confused. Any help to adapt their solution to my slightly different case would be appreciated.

EDIT: To clarify why I am confused, this is my code:

def compute_value(i):
    return i
results = []
def a_function(i):
    results.append(compute_value(i))
if __name__ == '__main__':
    pool = Pool()
    pool.map(a_function, range(10))

But when I print(results), I just get the output [] [] [].

Upvotes: 1

Views: 337

Answers (1)

nosuchthingasmagic
nosuchthingasmagic

Reputation: 246

Why not use something like this?

pool = Pool()
results = pool.map(compute_value, range(n_iterations))
print(results)

Upvotes: 2

Related Questions