[英]python multiprocessing on windows, if __name__ == “__main__”
[英]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.