gpt4 book ai didi

具有多处理功能的 Python 代码在 Windows 上不起作用

转载 作者:可可西里 更新时间:2023-11-01 09:37:43 25 4
gpt4 key购买 nike

以下纯初学者代码在 Ubuntu 14.04(Python 2.7.6)和 Cygwin(Python 2.7.8)上 100% 运行良好,但它在 Windows 64 位(Python 2.7.8)上挂起。我在使用 multiprocessing 包的另一个片段中观察到了同样的情况。

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."

我想知道这段代码有什么问题吗?

非常感谢您的帮助。

福斯托

最佳答案

根据您运行 Python 的方式,您可能需要使用 freeze_support在 Windows 上:

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()

另见 programming guidelines on Windows .

关于具有多处理功能的 Python 代码在 Windows 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27277063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com