簡體   English   中英

沒有“if __name__ =='__ main__'的python3.x多處理循環:”

[英]python3.x multiprocessing cycling without “if __name__ == '__main__':”

我有這個文件(它沒有任何有用的工作,它只用於學習):

import multiprocessing,sys
def parent(numproc=2):
    print ('at start')
    childs=[]
    print ('bfore Pipe')
    (parentEnd,childEnd)=multiprocessing.Pipe()
    i=0
    print ('printing i:',i)
    child=multiprocessing.Process(target=child_proc, args=(childEnd,i))
    print ('created child')
    child.start()
    print ('started child')
    print ('joining child')
    child.join()
    print ('joined child')
    print ('exeted from for i in childs')
    mins=[1,2]
    print ('task ended. result: ',min(mins))
def child_proc(pipe,name):
    pass
if __name__ == '__main__':
    parent()

以這種形式運行完美:

at start
bfore Pipe
printing i: 0
created child
started child
joining child
joined child
exeted from for i in childs
task ended. result:  1

但如果我放入文件的末尾而不是

if __name__ == '__main__':
    parent()

只要

parent()

它落在周期......

at start
bfore Pipe
printing i: 0
created child
started child
joining child
at start
bfore Pipe
printing i: 0
created child
started child
joining child
at start
bfore Pipe
printing i: 0
created child
started child
joining child
Traceback (most recent call last):

為什么?! 這個if條款有什么不同?

這是MS Windows上的multiprocessing問題:主模塊由子任務導入,因此任何代碼都不受if __name__ . . .保護if __name__ . . . if __name__ . . . 子句再次運行,導致無限循環。

子進程具有以下__name____parents_main__而不是__main__了。 這就是為什么在__name__變量時,您的進程不會循環。

有關這方面的更多信息,請參閱安全導入主模塊一章

暫無
暫無

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

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