简体   繁体   English

多处理“池”挂起正在运行的程序

[英]Multiprocessing “Pool” hangs on running program

I have written a program to use the "Pool" from multiprocessing python package,but it keeps hanging the kernel.(I am using Jupyter with Anaconda,by the way) 我编写了一个程序来使用多处理python包中的“Pool”,但是它一直挂着内核。(顺便说一下,我正在使用Jupyter和Anaconda)

I tried using a function from an imported package like "math",which works perfectly,but, the moment i use a function i created in the same python file it doesn't work. 我尝试使用像“math”这样的导入包中的函数,它运行得很好,但是,当我使用我在同一个python文件中创建的函数时,它不起作用。

import multiprocessing as mp

def f(x):
   for i in x:
      return i+1

ar=[1,2,3,4,5]
def main():
    pool=mp.Pool(processes=4)
    pool.map(f,ar)
if __name__== '__main__':
    main()

It shows that the kernel is working,but the cpu usage sits at 0%. 它表明内核正在运行,但CPU使用率为0%。

The problem is ar is not within the local scope of your main function, it's above it. 问题是ar不在你的主函数的局部范围内,它在它之上。 Put it inside and it should work. 把它放在里面它应该工作。

from multiprocessing import Pool

def f(x):
    return x+1

if __name__ == '__main__':
    ar=[1,2,3,4,5]
    with Pool(4) as p:
        print(p.map(f, ar))

Also consider map is taking your iterable and assigning it across the processes, in essence it is doing the for loop for you. 还要考虑map正在进行迭代并在整个进程中分配它,本质上它正在为你做for循环。 Therefore you can access the x directly. 因此,您可以直接访问x。

And then last, using with as a context manager ensures your Pool closes when it is complete. 最后,使用with作为上下文管理器可确保您的池在完成后关闭。 [docs] [文档]

Edit: I edited and tested the above code and mine sends the correct values and closes properly. 编辑:我编辑并测试了上面的代码,我发送正确的值并正确关闭。

This code also works for me in both Spyder 3.2.6 and standard terminal. 此代码也适用于Spyder 3.2.6和标准终端。 Both snippets close out properly and don't hang on my machine. 两个片段都正常关闭,不会挂在我的机器上。

import multiprocessing as mp

def f(x):
    return x+1

def main():
    ar = [1,2,3,4,5]
    pool = mp.Pool(processes=4)
    print(pool.map(f, ar))

if __name__ == '__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM