首页 > 解决方案 > 多处理代码不产生结果

问题描述

我在 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

标签: pythonmultiprocessing

解决方案


您在 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方法的默认值chunksizewhenmap根据参数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 chunksizemap都会将您的iterable转换为 alist如果需要以获得它的长度。但本质上,chunksize使用的默认值是提交的作业数量的上限除以池大小的 4 倍。


推荐阅读