试图了解Python的Concurrent.Futures模块

Map*_*sis 5 python concurrency multithreading

我试图了解如何concurrent.futures在Python 3.2.2中使用该模块,并且一直在使用文档中的示例。当我尝试运用自己的理解时,我自己的例子失败了。我希望有人能帮助我走上正轨!

我希望能够设置多个同时运行但异步运行的进程。我的进程不返回任何东西。为了模拟这一点,我编写了一个简单的示例:

import concurrent.futures

fred = [1,2,3,4,5,6,7,8,9,10]

def f(x):
    print(x * x)

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for num in fred:
            executor.submit(f, num)

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

此代码运行(在4核Windows XP机器上)并返回:

1 4 9 16 25

...但随后挂起。

显然我做错了。那么,让Python在进程池中运行进程的正确方法是什么?我不想使用这种executor.map方法,因为我的过程没有任何回报。

还是……我是否必须通过返回流程TrueFalse(或其他方式)伪造它?

谢谢!

小智 2

我不太明白为什么你不想使用executor.map...我用一个没有返回任何内容的函数尝试了它(f实际上是用你的函数)并且它工作得很好...

现在,当您使用 运行它时map,它实际上不会打印值,但这里是f打印值的函数版本:

import concurrent.futures

fred = [1,2,3,4,5,6,7,8,9,10]

def f(x):
    return x * x

with concurrent.futures.ProcessPoolExecutor() as executor:
    for num in executor.map(f, fred):
        print(num)
Run Code Online (Sandbox Code Playgroud)