傻瓜式 Python 多处理

标签 python multiprocessing

<分区>

我试图找到一个简单的例子,清楚地显示一个单一的任务被划分为多处理。

坦率地说,许多示例都过于复杂,因此使流程更难玩。

有人愿意分享他们的突破性样本或例子吗?

最佳答案

你的基本例子是这样的:

>>> import multiprocessing as mp
>>> from math import sqrt
>>> worker_pool = mp.Pool()
>>> jobs = [0, 1, 4, 9, 16, 25] 
>>>
>>> # calculate jobs in blocking batch parallel
>>> results = worker_pool.map(sqrt, jobs)
>>> results
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
>>>
>>> # calculate jobs in asynchronous parallel
>>> results = worker_pool.map_async(sqrt, jobs)
>>> results.get()
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
>>>
>>> # calculate jobs in parallel with an unordered iterator
>>> results = worker_pool.imap_unordered(sqrt, jobs)
>>> list(results)  # NOTE: results may return out of order
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
>>>
>>> # a single blocking job on another process
>>> worker_pool.apply(sqrt, [9])
3.0
>>> # a single asynchronous job on another process
>>> y = worker_pool.apply_async(sqrt, [9])
>>> y.get()
3.0
>>> # the same interface exists for threads
>>> thread_pool = mp.dummy.Pool()
>>> thread_pool.map(sqrt, jobs)
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
>>>
>>> # finishing up, you should shut down your pools
>>> worker_pool.close()
>>> worker_pool.join()
>>> thread_pool.close()
>>> thread_pool.join()

如果您不想批量并行,但想要更复杂的东西,示例可能会变得更复杂。

关于傻瓜式 Python 多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32594083/

相关文章:

java - 如何将新的 JVM 附加到生成的 Python 进程?

python - 对 setup.py 中的 package_dir 和 packages 设置感到困惑

python - 获取 ZeroDivisionError : float division in python

python - 需要返回协方差的 Python 多项式拟合函数

python - 用 Nose 测试 python 多处理池代码

Python池映射和选择进程数

python - Python中的 double 浮点值?

python - 如何将python应用程序连接到在线数据库

python - python中的多处理被阻止

Python 多进程问题进程未启动