Python多处理-空队列和池冻结的问题

时间:2019-02-05 22:32:49

标签: python process queue multiprocessing pool

我在python多处理方面遇到问题

python版本3.6.6

在Windows 7上使用Spyder IDE

1。

队列没有被填充->每次我尝试读取它时,它都是空的。在我读过的某个地方,我必须在进程join()之前先获取它,但它并不能解决问题。

from multiprocessing import Process,Queue

# define a example function
def fnc(i, output):    
    output.put(i)    

if __name__ == '__main__':
    # Define an output queue
    output = Queue()

    # Setup a list of processes that we want to run
    processes = [Process(target=fnc, args=(i, output)) for i in range(4)]
    print('created')

    # Run processes
    for p in processes:
        p.start()
    print('started')

    # Exit the completed processes        
    for p in processes:
        p.join()

    print(output.empty())
    print('finished')

>>>created
>>>started
>>>True
>>>finished

我希望输出不会为空。

如果我将其从.join()更改为

    for p in processes:
        print(output.get())
        #p.join()

冻结

2。

我遇到的下一个问题是pool.map()-它冻结并且没有机会超过内存限制。我什至不知道如何调试这种简单的代码。

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)
    print('Pool created')
    # print "[0, 1, 4,..., 81]"
    print(pool.map(f, range(10))) # it freezes here

希望在一个主题中有两个问题没什么大不了的

1 个答案:

答案 0 :(得分:0)

问题显然是Spyder的IPython控制台。当我同时从cmd运行它们时,它可以正确执行。


解决方案

要在Spyder中进行调试,请将.dummy添加到多处理导入中

from multiprocessing.dummy import Process,Queue

它不会被更多的处理器执行,但是您将获得结果并且可以实际看到输出。调试完成后,只需删除.dummy,将其放置在另一个文件中,然后导入并以函数形式调用它

multiprocessing_my.py

from multiprocessing import Process,Queue

# define a example function
def fnc(i, output):
    output.put(i)
    print(i)

def test():
    # Define an output queue
    output = Queue()
    # Setup a list of processes that we want to run
    processes = [Process(target=fnc, args=(i, output)) for i in range(4)]
    print('created')
    # Run processes
    for p in processes:
        p.start()
    print('started')
    # Exit the completed processes

    for p in processes:    
        p.join()

    print(output.empty())
    print('finished')

    # Get process results from the output queue
    results = [output.get() for p in processes]
    print('get results')
    print(results)

test_mp.py

通过选择代码并按ctrl + Enter执行

import multiprocessing_my

multiprocessing_my.test2()

...

In[9]: test()
    created
    0
    1
    2
    3
    started
    False
    finished
    get results
    [0, 1, 2, 3]