Python's multiprocessing map_async generates error on Windows

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 16:35:24

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

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.

See: http://docs.python.org/library/multiprocessing.html#windows

EDIT this works for me:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!