本文介绍了Python的多处理map_async在Windows上产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码在Unix上可以正常使用,但是在Windows 7上会生成multiprocessing.TimeoutError(两个操作系统都使用python 2.7).

The code below works perfectly on Unix but generates a multiprocessing.TimeoutError on Windows 7 (both OS use python 2.7).

知道为什么吗?谢谢.

from multiprocessing import Pool

def increment(x):
    return x + 1

def decrement(x):
    return x - 1

pool = Pool(processes=2)
res1 = pool.map_async(increment, range(10))
res2 = pool.map_async(decrement, range(10))

print res1.get(timeout=1)
print res2.get(timeout=1)

推荐答案

您需要将实际的程序逻辑放在if __name__ == '__main__':块的旁边.

You need to put your actual program logic in side a if __name__ == '__main__': block.

在Unixy系统上,Python分叉,产生多个要使用的进程. Windows没有分叉. Python必须启动一个新的解释器,然后重新导入所有模块.这意味着每个子流程都将重新导入您的主模块.对于您编写的代码,重新导入该模块将使每个新启动的进程启动其自己的进程.

On Unixy systems, Python forks, producing multiple processes to work from. Windows doesn't have fork. Python has to launch a new interpreter and re-import all your modules instead. This means that each subprocess will reimport your main module. For the code you've written reimporting the module will cause each newly launched processes to launch processes of its own.

请参阅: http://docs.python.org/library/multiprocessing.html# Windows

编辑,这对我有用:

from multiprocessing import Pool

def increment(x):
    return x + 1

def decrement(x):
    return x - 1

if __name__ == '__main__':
    pool = Pool(processes=2)
    res1 = pool.map_async(increment, range(10))
    res2 = pool.map_async(decrement, range(10))

    print res1.get(timeout=1)
    print res2.get(timeout=1)

这篇关于Python的多处理map_async在Windows上产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 18:27