2014-12-03 55 views
3

以下天真的絕對初學者代碼在Ubuntu 14.04(Python 2.7.6)和Cygwin(Python 2.7.8)上運行得很好,但它掛在Windows 64位( Python 2.7.8)。我觀察到與使用多處理包的另一個片段相同。帶有多處理功能的Python代碼在Windows上不起作用

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

我不知道什麼不對的代碼?

非常感謝您的任何幫助。

福斯托

回答

0

取決於您如何運行Python,你可能需要在Windows上使用freeze_support

一個需要if __name__ == '__main__'線主模塊後直接調用該函數。例如:

from multiprocessing import Process, freeze_support 

def f(): 
    print 'hello world!' 

if __name__ == '__main__': 
    freeze_support() 
    Process(target=f).start() 

又見programming guidelines on Windows

+0

嗨費迪南德,謝謝! 事實上,我發現代碼最終在沒有freeze_support()調用的情況下在Windows上運行,只要我給它足夠的時間(可以說是時間浪費了一段時間,我可以說)完成。它沒有懸掛;在Windows上執行的時間比在Cygwin上執行時間長14倍。問題不在於Windows;我是不耐煩的。 ;-) 謝謝, – 2014-12-03 17:15:25