简体   繁体   English

多处理循环

[英]Multiprocessing For Loop

I have a few CPUs at my disposal on a virtual machine.我在虚拟机上有几个 CPU 可供使用。 I have a rather simple for loop to compute, which I would like to multiprocess as it computes separate parts.我有一个相当简单的 for 循环来计算,我想在计算单独的部分时对其进行多处理。

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. 这个问题的答案考虑了有一个你想要遍历的 data_inputs 列表的情况。 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 [] [] [].但是当我打印(结果)时,我只得到 output [] [] []。

Why not use something like this?为什么不使用这样的东西呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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