【问题标题】:Python Multiprocessing iterates over scriptPython多处理迭代脚本
【发布时间】:2017-11-17 12:40:33
【问题描述】:

我正在尝试使用 multiprocessing.pool,它似乎工作正常,除了整个脚本一次又一次循环......

我的代码 -

from multiprocessing import Pool

print "at top!"

arr = [30, 30, 30, 30]

def fib(num):
    if num == 0 or num == 1: return 1
    else: return (fib(num - 1) + fib(num - 2))

def main():
    print "start"
    pool = Pool(processes=4)
    result = [pool.apply_async(fib, args=(arr[i],)) for i in range(4)]
    pool.close()
    pool.join()
    for res in result:
        print res.get()
    print "end"


if __name__ == '__main__':
    main()


print "end of program ?"

它返回的是这个 -

at top!
start
at top!
end of program ?
at top!
end of program ?
at top!
end of program ?
at top!
end of program ?
1346269
1346269
1346269
1346269
end
end of program ?

我不想要的是重复的at top !end of program

我希望主程序在该点冻结并仅在所有计算完成后继续。

PS。我在 Windows 10、64 位上运行它。 Python 2.7 32 位。

提前致谢。

【问题讨论】:

  • 奇怪,当我运行这个(在python2.7中)时,我只得到at topend of program ?一次。

标签: python windows multiprocessing python-multiprocessing


【解决方案1】:

如果您正在运行 windows,这是预期的,python windows 产生进程的方式:脚本被导入的次数与产生的进程一样多。因此,如果您不缩进(在脚本顶层),则不能只有一个 "at top" 打印。当然,print "end of program ?" 也是如此。

(这在 Linux 上不会发生,这解释了用户的 cmets 说他们无法重现)

这也是您必须使用 if __name__ == '__main__' 测试来保护您的 main 的原因。因此,要获得预期的输出,您必须这样做:

if __name__ == '__main__':
    print("at top!")
    main()
    print("end of program")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2017-07-25
    • 2023-01-31
    • 2019-08-14
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多