Python多重处理apply_async永远不会在Windows 7上返回结果 [英] Python multiprocessing apply_async never returns result on Windows 7

查看:410
本文介绍了Python多重处理apply_async永远不会在Windows 7上返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循一个非常简单的多处理示例:

I am trying to follow a very simple multiprocessing example:

import multiprocessing as mp

def cube(x):
    return x**3

pool    = mp.Pool(processes=2)
results = [pool.apply_async(cube, args=x) for x in range(1,7)]

但是,在我的Windows机器上,我无法获得结果(在ubuntu 12.04LTS上,它运行良好).

However, on my windows machine, I am not able to get the result (on ubuntu 12.04LTS it runs perfectly).

如果我检查results,则会看到以下内容:

If I inspect results, I see the following:

[<multiprocessing.pool.ApplyResult object at 0x01FF0910>,
 <multiprocessing.pool.ApplyResult object at 0x01FF0950>,
 <multiprocessing.pool.ApplyResult object at 0x01FF0990>,
 <multiprocessing.pool.ApplyResult object at 0x01FF09D0>,
 <multiprocessing.pool.ApplyResult object at 0x01FF0A10>,
 <multiprocessing.pool.ApplyResult object at 0x01FF0A50>]

如果我运行results[0].ready(),我总是会得到False.

If I run results[0].ready() I always get False.

如果我运行results[0].get(),则python解释器会冻结,等待获取永远不会出现的结果.

If I run results[0].get() the python interpreter freezes, waiting to get the result that never comes.

该示例非常简单,因此我认为这是与OS相关的低级错误(我在Windows 7上).但是也许其他人有更好的主意吗?

The example is as simple as it gets, so I am thinking this is a low level bug relating to the OS (I am on Windows 7). But perhaps someone else has a better idea?

推荐答案

这里有两个错误.首先,在Windows上运行时,必须在if __name__ == "__main__":防护内,声明Pool.其次,即使仅传递一个参数,也必须将args关键字参数传递给序列.因此,将它们放在一起:

There are a couple of mistakes here. First, you must declare the Pool inside an if __name__ == "__main__": guard when running on Windows. Second, you have to pass the args keyword argument a sequence, even if you're only passing one argument. So putting that together:

import multiprocessing as mp

def cube(x):
    return x**3

if __name__ == "__main__":
    pool    = mp.Pool(processes=2)
    results = [pool.apply_async(cube, args=(x,)) for x in range(1,7)]
    print([result.get() for result in results])

输出:

[1, 8, 27, 64, 125, 216]

哦,就像moarningsun提到的那样,multiprocessing 在交互式解释器中效果不佳 :

Oh, as moarningsun mentions, multiprocessing does not work well in the interactive interpreter:

注意

此软件包中的功能需要__main__模块为 由儿童进口.编程指南中对此进行了介绍 但是这里值得指出.这意味着一些例子, 例如multiprocessing.Pool示例在 交互式口译员.

Functionality within this package requires that the __main__ module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.Pool examples will not work in the interactive interpreter.

因此,您实际上需要将代码作为脚本执行才能正确测试.

So you'll need to actually execute the code as a script to test it properly.

这篇关于Python多重处理apply_async永远不会在Windows 7上返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆