加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python的多处理map_async在Windows上生成错误

发布时间:2020-12-20 13:30:08 所属栏目:Python 来源:网络整理
导读:下面的代码在Unix上完美运行,但在 Windows 7上生成多处理.TimeoutError(两个操作系统都使用python 2.7). 知道为什么吗?谢谢. from multiprocessing import Pooldef increment(x): return x + 1def decrement(x): return x - 1pool = Pool(processes=2)res1
下面的代码在Unix上完美运行,但在 Windows 7上生成多处理.TimeoutError(两个操作系统都使用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__’:block的旁边.

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

见: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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读