python - 多处理代码不产生结果
问题描述
我在 Python 中运行以下代码。该代码显示了如何在 Python 中使用多处理的示例。但它没有打印结果(第 16 行),仅打印数据集(第 9 行)并且内核继续运行。我认为应该立即生成结果,因为代码通过多处理使用 cpu 的各个内核,因此应该可以快速执行代码。有人可以告诉是什么问题吗??
from multiprocessing import Pool
def square(x):
# calculate the square of the value of x
return x*x
if __name__ == '__main__':
# Define the dataset
dataset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
# Output the dataset
print ('Dataset: ' + str(dataset)) # Line 9
# Run this with a pool of 5 agents having a chunksize of 3 until finished
agents = 5
chunksize = 3
with Pool(processes=agents) as pool:
result = pool.map(square, dataset, chunksize)
# Output the result
print ('Result: ' + str(result)) # Line 16
解决方案
您在 Windows 下运行。查看启动 Jupyter 的控制台输出。您将看到以下 5 个实例(池中有 5 个进程):
AttributeError: 无法在 <module ' main ' (built-in)>上获取属性 'square'
您需要将工作函数放在一个文件中,例如,workers.py
与 Jupyter 代码位于同一目录中:
工人.py
def square(x):
# calculate the square of the value of x
return x*xdef square(x):
然后从您的单元格中删除上述函数,然后添加:
import workers
接着:
with Pool(processes=agents) as pool:
result = pool.map(workers.square, dataset, chunksize)
笔记
有关构造函数的chunksize
参数,请参阅我对您的帖子的评论。Pool
方法的默认值chunksize
whenmap
根据参数None
或多或少地计算如下iterable
:
if not hasattr(iterable, '__len__'):
iterable = list(iterable)
if chunksize is None:
chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
if extra:
chunksize += 1
所以我在一个细节上说错了:无论您是否指定 a chunksize
,map
都会将您的iterable转换为 alist
如果需要以获得它的长度。但本质上,chunksize
使用的默认值是提交的作业数量的上限除以池大小的 4 倍。
推荐阅读
- php - 我想从此查询中排除一些公司名称
- kubernetes - 从 kubernetes 内部的 InfluxDb 导出数据
- java - 我们可以使用 Liquibase 监控数据库表中新添加的数据吗?
- apache-spark - 我们如何在 Spark 结构化流 2.4.4 中缓存/持久化数据集
- apache-spark - Kubernetes 与 Spark 与 Kubernetes 上的 Spark
- ios - iOS PencilKit 不绘图
- android - 显示默认错误,即提供所有值简而言之 JSON 不会将值放入服务器
- kotlin - Kotlin 中 ::class 和 ::class.java 有什么区别?
- java - 我如何将推送令牌存储到数据库
- ios - 从领域查询中设置表部分标题