我有一些代码,如下所示:
for item in list:
<bunch of slow python code, depending only on item>
我想通过并行化循环来加快速度。通常是multiprocessing
module 非常适合这个(请参阅 this question 的答案),但它是在 python 2.6 中添加的,而我一直在使用 2.4。
在 python 2.4 中并行化 python 循环的最佳方法是什么?
最佳答案
您可能正在寻找“ fork ”,这样可以轻松使用特定项目。
- http://docs.python.org/release/2.4/lib/os-process.html
- http://en.wikipedia.org/wiki/Fork_%28operating_system%29#Example_in_Python
不过,您的 for 循环需要看起来有点不同——您希望在 fork 返回零时立即中断。
import os
L = ["a", "b", "c"]
for item in L:
pid = os.fork()
if pid == 0: break
else: print "Forked:", pid
if pid != 0: print "Main Execution, Ends"
else: print "Execution:", item
关于python - 在 python 2.4 中并行化循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17870778/