首页 > 解决方案 > 在函数中使用多处理

问题描述

我想从下面获取工作代码并将其放入一个函数中。

import multiprocessing as mp

def parameters(x,n):
    for i in x:
        yield (i,n)

def power(a):
    x, n = a
    
    return x**n

if __name__ == '__main__':
    p = [i for i in range(1000)]
    p = parameters(p,2)
    agents = 4
    chunk = 10

    with mp.Pool(processes = agents) as pool:
        o = pool.map(power,p,chunksize = chunk)
    
    print(o)

这样我就可以随时调用它。我试着做这样的事情:

import multiprocessing as mp

def parameters(x,n):
    for i in x:
        yield (i,n)

def power(a):
    x, n = a
    
    return x**n

def calculate(s,n):
    p = [i for i in range(s)]
    p = parameters(p,n)

    agents = 4
    chunk = 10

    with mp.Pool(processes = agents) as pool:
        o = pool.map(power,p,chunksize = chunk)

    return o

print(calculate(1000,2))

但是,这根本不起作用,它告诉我另一个进程在一个进程结束之前已经开始。但是上面的代码确实有效。有没有办法将此代码正确地放入函数中?如果不使用此设置,那么使用什么设置?

标签: python-3.xmultiprocessing

解决方案


确保保护只应在主进程中运行的代码if __name__ == '__main__':。此代码有效:

import multiprocessing as mp

def parameters(x,n):
    for i in x:
        yield (i,n)

def power(a):
    x, n = a
    return x**n

def calculate(s,n):
    p = [i for i in range(s)]
    p = parameters(p,n)

    agents = 4
    chunk = 10

    with mp.Pool(processes = agents) as pool:
        o = pool.map(power,p,chunksize = chunk)

    return o

if __name__ == '__main__':
    print(calculate(1000,2))

如果没有if,则会引发以下错误:

RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

推荐阅读