python - 试图理解 Python 的 Concurrent.Futures 模块

标签 python multithreading concurrency

我正在尝试了解如何在 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 方法,因为我的流程没有任何返回。

或者……我是否必须通过让进程返回 TrueFalse(或其他)来伪造它?

谢谢!

最佳答案

我不太明白你为什么不想使用 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/

相关文章:

c# - 多线程和 ProgressBar

java - 发生之前和易变变量

python - wxPython:使用 Show() 和 Hide()

python - 如何在 App Engine 中使用导入内存缓存的库

Python If 语句在测试 1 到 10 之间的数字时不起作用

c# - ConcurrentBag 字符串并在 Parallel.ForEach 中使用 .Contains

Java JFrame removeall 挂起应用程序

python - 如何将日期偏移到月初?

ruby - Log4r 在 Rails 4 应用程序中实际上是线程安全的吗?

multithreading - 从 Ada 的 protected 对象访问私有(private)类型