python - 尝试跨 n 个节点并行化 python 循环写入字典

标签 python multithreading dictionary parallel-processing

我正在尝试将 python 循环有效地并行化为 n 个线程。我对最好的方法是什么感到有点困惑。其他问题是每个线程都需要写入字典(虽然永远不会在同一个位置),并且每个线程都必须执行循环的 24/n 次迭代(尽管我很确定大多数 pyhon 库会处理这个问题对我来说)。

代码(简化):

n=<number of threads input by user>
mySets=[ str(x) for x in range(1,25) ]
myDict={}

// Start of parallelization
for set in mySets:

    //Performs actions on the set
    //Calls external c++ code on the set and gets a result back
    //processes the result
    myDict[set]=result

// End parallelization

// Process the results to output

我在 unix 环境中,但最好在 Windows 或 MAC 上不会有问题。我的其余代码是可移植的,我真的不希望它停止。

我看到这个线程:Parallelize a loop in python 2.4 但我不认为 fork 是我想要的,因为我希望用户指定可用的节点数。

我还查看了多处理库,我很确定这是我想要的,但似乎每个人都将他们的代码放入一个函数中——我想避免这种情况……它有很多代码而且它会很乱。

我也看到了joblib,但是我不清楚它和multiprocessing库有什么区别。以及一个与另一个相比的好处是什么。

感谢您的帮助!

最佳答案

您可以使用 mutliprocessing.pool.Pool .

这是一些伪代码:

from multiprocessing.pool import Pool


def do_something(n, sets):
    out = dict()

    with Pool(processes=n) as pool:
        results = pool.map(cpp_computation_function, sets)
        for set, result in zip(sets, results):
            out[set] = result

    return out

关于python - 尝试跨 n 个节点并行化 python 循环写入字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45243190/

相关文章:

python - 如何处理 celery 的 Task.map 中的错误

python - 用字符串在字典中找到最近的键?

algorithm - 使用 Map/Reduce 算法对单词进行计数

python - 使用 Selenium Web 驱动程序提取我想要的值时遇到问题

python - 在 python 3.6 中安装 GDAL

c# - .NET WinForms 多线程行为 : Setting property value in ThreadPool. QueueUserWorkItem 尽管有异常

linux - 关于glibc中malloc实现的问题

python - Scikit学习中的线性回归和梯度下降?

python - 为什么我不能删除在 ProgramData 中创建的目录?

Java ServiceExecutor 终止条件