【问题标题】:Python3: Parallel Processing using Yield generatorPython3:使用产量生成器进行并行处理
【发布时间】:2018-08-14 19:23:33
【问题描述】:

我将有一个函数会产生值,而另一个函数将对这些产生的值执行一些操作。我想使用并行处理(即 concurrent.futures.ProcessPoolExecutor 或 Multiprocessing)进行操作。过程的顺序很重要,即第一个输出应该是第一个输入。伪代码如下:

def square(x):
    return x**2

def numbers():
    for i in range(1,10):
        yield i

if __name__ == '__main__':
    with concurrent.futures.ProcessPoolExecutor(4) as executor:        
       for i in executor.map(square, numbers):
           print(i)

我有以下问题,但没有找到太多解释:

1) 如何映射产量生成器和函数

2) 如果 ProcessPoolExecutor 是一个正确的选择,因为它是异步的并且会搞砸 输入输出的顺序。

3) 如何使用多处理池和生成器。池映射方法不是 为我打印任何输出。我很难理解 Multiprocessing Pool的应用。

if __name__ == '__main__':
    with mp.Pool(4) as p:        
        print(p.map(square, numbers))

如果有人能帮助我理解并行处理,我将不胜感激。

附:我知道如果将生成器函数转换为数字列表并映射函数square,则易于使用和理解多处理;而且一切正常,但我不想将整个数据加载到内存中。

【问题讨论】:

    标签: python-3.x concurrency python-multiprocessing


    【解决方案1】:

    您的两个示例都有错误。您必须调用numbers 函数才能真正生成生成器:

    if __name__ == '__main__':
        with concurrent.futures.ProcessPoolExecutor(4) as executor:        
           for i in executor.map(square, numbers()):
               print(i)
    

    if __name__ == '__main__':
        with mp.Pool(4) as p:        
            print(p.map(square, numbers()))
    

    【讨论】:

    • 哦!这很简单,这为我解决了一个非常大的问题。谢谢你。我实际上不知道该怎么做。我的印象是我必须编写一个循环并在该循环中调用numbers 来获取值。但这很整洁。
    • 祝您接下来的并发旅程好运 :)
    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多