簡體   English   中英

如何在運行完整腳本的python中停止多處理

[英]How to stop multiprocessing in python running for the full script

我在python中有以下代碼:

import multiprocessing
import time

print "I want this to show once at the beggining"

def leaveout():
    print "I dont Want This to Show"

def hang(input1):
        print "I want this to show 3 times"
        print "Number = %s" % input1

def main():
    p = multiprocessing.Process(target=hang, args=("0"))
    p.start()
    p1 = multiprocessing.Process(target=hang, args=("1"))
    p1.start()
    p2 = multiprocessing.Process(target=hang, args=("2"))
    p2.start()
    p.join()
    p1.join()
    p2.join()

if __name__ == '__main__':
    main()

print "I want this to show once at the end"

我的目標是在成功發生的三個實例中對hang函數進行多進程處理。 我的問題是,main函數還在以下輸出中重新運行了整個腳本的三個實例:

c:\Evopt>python multiprocessingprac.py
I want this to show once at the beggining
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 2
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 1
I want this to show once at the beggining
I want this to show once at the end
I want this to show 3 times
Number = 0
I want this to show once at the end

我該如何阻止這種情況發生?

生成新進程時,Windows將創建一個空白進程。 然后,在生成的過程中加載了一個新的Python解釋器,並為其提供了相同的代碼庫來進行解釋。

這就是為什么您看到重復的打印語句正在執行的原因。 由於它們是頂級表達式,因此每次過程將評估該代碼時都將執行它們。

在Unix OS中,這沒有被觀察到,因為它實現了完全不同的進程創建機制( fork策略),該機制不需要在子進程中再次加載新的Python解釋器。

要解決您的問題,您需要從腳本中刪除print( ... )表達式,並將其移至main函數中。

def main():
    print("I want this to show once at the beggining")

    p0 = multiprocessing.Process( ... )
    p0.start() 

    ...

    p2.join()

    print("I want this to show once at the end")

您可以在多處理文檔中閱讀有關流程啟動策略的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM