首页 > 解决方案 > Python多处理while循环,返回和追加输出

问题描述

我想并行化一个概念上简单的代码,但是我发现的所有其他线程都太复杂了,我不明白如何将它们应用于我的案例,或者即使它们适用。

在我的代码中,通过 while 循环调用具有多个参数的函数,并从循环返回输出和退出条件。我想并行化while循环。我正在使用 Python 3.7.3。

这是一个简化的示例:

import multiprocessing as mp
import numpy as np
import time

def foo(i, arg1, arg2):
    n = np.random.rand()
    n = arg1*n + arg2
    if n > 0.9:
        stop = True
    else:
        stop = False
    return [i, n], stop

if __name__ == '__main__':
    i = 0
    stop = False
    output = list()
    while not stop:
        out, stop = foo(i, 1, 0)
        i = i + 1
        if not stop:
            output.append(out)
    print(np.asarray(output))

输出:

[[ 0.          0.25295033]
 [ 1.          0.53795096]
 [ 2.          0.48774803]
 [ 3.          0.09281972]
 [ 4.          0.75053227]
 [ 5.          0.30367072]
 [ 6.          0.57043762]
 [ 7.          0.4589554 ]
 [ 8.          0.33231446]
 [ 9.          0.76805717]
 [10.          0.22486246]
 [11.          0.69499273]
 [12.          0.67616563]]

编辑。我想“碰撞”这个线程,因为这是我真正需要帮助的事情,我不能自己做。Meta-etiquette 说我应该通过为问题添加价值来进行编辑,但我认为我不能添加任何其他内容:我只需要并行化呈现的代码。我真的很感激任何(实际的)反馈。

标签: while-loopmultiprocessingreturn

解决方案


推荐阅读