简体   繁体   中英

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 [] [] [].

Why not use something like this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM