具有多处理功能的Python代码在Windows上不起作用 [英] Python code with multiprocessing does not work on Windows
问题描述
下面的幼稚,绝对入门代码在Ubuntu 14.04(Python 2.7.6)和Cygwin(Python 2.7.8)上可以100%很好地工作,但是在Windows 64位(Python 2.7.8)上却挂起了.我已经观察到使用 multiprocessing 软件包的其他代码片段也是如此.
The following naive, absolute-beginner code works 100% well on Ubuntu 14.04 (Python 2.7.6) and Cygwin (Python 2.7.8) but it hangs on Windows 64-bit (Python 2.7.8). I have observed the same with another snippets using the multiprocessing package.
from multiprocessing import Process, Queue
from time import time
def WallisPi(N,out): # Pi by the (slowly convergent) Wallis method.
prod = 1.0
for i in xrange(2,N,2):
prod = prod*(i**2)/((i+1)**2)
prod = 2.0e0*prod*(i+1)
out.put(prod)
return 0
if __name__ == '__main__':
T = [15000000, 25000000, 30000000, 40000000]
ti = time()
q1 = Queue()
p1 = Process(target=WallisPi, args=(T[0],q1))
p1.start()
q2 = Queue()
p2 = Process(target=WallisPi, args=(T[1],q2))
p2.start()
q3 = Queue()
p3 = Process(target=WallisPi, args=(T[2],q3))
p3.start()
q4 = Queue()
p4 = Process(target=WallisPi, args=(T[3],q4))
p4.start()
p = [p1, p2, p3, p4]
for item in p:
item.join()
q = [q1, q2, q3, q4]
print "\n"
Num = len(q)
for i in range(0,Num):
print "Pi at ",T[i], "terms = ", q[i].get()
tf = time()
print "\nElapsed time: ", round((tf-ti),2), " secs."
我想知道这段代码怎么了?
I wonder what's wrong with this code?
在此先感谢您的帮助.
Fausto
推荐答案
Depending on how you run Python, you might need to use freeze_support
on Windows:
需要在主模块的
if __name__ == '__main__'
行之后直接调用此函数.例如:
One needs to call this function straight after the
if __name__ == '__main__'
line of the main module. For example:
from multiprocessing import Process, freeze_support
def f():
print 'hello world!'
if __name__ == '__main__':
freeze_support()
Process(target=f).start()
另请参见Windows上的编程指南.
See also the programming guidelines on Windows.
这篇关于具有多处理功能的Python代码在Windows上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!