【问题标题】:Python multiprocessing - problem with empty queue and pool freezingPython多处理 - 空队列和池冻结问题
【发布时间】:2019-02-05 22:32:49
【问题描述】:

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

python 版本 3.6.6

在 Windows 7 上使用 Spyder IDE

1.

队列没有被填充 -> 每次我尝试阅读它时,它都是空的。在某处我读到,我必须在处理 join() 之前 get() 它,但它没有解决它。

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

希望在一个主题中有两个问题不是什么大问题

【问题讨论】:

  • 除了使用queue.empty() 检查(不可靠)您的代码看起来不错。 Spyder 至少因多处理问题而出名。尝试从终端运行您的代码。

标签: python process queue multiprocessing pool


【解决方案1】:

显然问题出在 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]

【讨论】:

    猜你喜欢
    • 2014-08-25
    • 1970-01-01
    • 2016-04-18
    • 2012-01-23
    • 1970-01-01
    • 2013-05-17
    • 2020-02-19
    • 1970-01-01
    • 2021-09-30
    相关资源
    最近更新 更多