我正在尝试了解如何在 Python 3.2.2 中使用 concurrent.futures
模块,并且一直在研究文档中的示例。当我尝试应用我的理解时,我自己的例子失败了。我希望有人能帮助我走上正轨!
我希望能够设置多个并发但异步运行的进程。我的过程不返回任何东西。为了模拟这个,我写了一个简单的例子:
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()
此代码运行(在 4 核 Windows XP 机器上)并返回:
1 4 9 16 25
...但随后挂起。
显然我做错了什么。那么,让 Python 在进程池中运行进程的正确方法是什么?我不想使用 executor.map
方法,因为我的流程没有任何返回。
或者……我是否必须通过让进程返回 True
或 False
(或其他)来伪造它?
谢谢!
最佳答案
我不太明白你为什么不想使用 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)
关于python - 试图理解 Python 的 Concurrent.Futures 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8081149/