【问题标题】:Python code with multiprocessing does not work on Windows具有多处理功能的 Python 代码在 Windows 上不起作用
【发布时间】:2014-12-03 16:43:08
【问题描述】:

以下天真、绝对初学者的代码在 Ubuntu 14.04 (Python 2.7.6) 和 Cygwin (Python 2.7.8) 上运行良好,但在 Windows 64 位 (Python 2.7.8) 上挂起。我在另一个使用 multiprocessing 包的 sn-ps 中观察到了同样的情况。

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 linux windows multiprocessing


    【解决方案1】:

    根据您运行 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

    【讨论】:

    • 嗨,费迪南德,谢谢!事实上,我发现代码最终可以在没有 freeze_support() 调用的情况下在 Windows 上运行,只要我给它足够的时间(我可以说是一段令人讨厌的时间)来完成。它没有挂。在 Windows 上执行的时间比在 Cygwin 上执行的时间长 14 倍。问题不在于 Windows;是我不耐烦。 ;-) 谢谢,
    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多