我有这个文件(它没有做任何有用的工作,只是为了学习):
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子句有什么不同?
答案 0 :(得分:5)
这是MS Windows上multiprocessing
的问题:主要模块由子任务导入,因此任何不受if __name__ . . .
子句保护的代码都会再次运行,从而导致无限循环。
答案 1 :(得分:2)
子流程具有以下__name__
:__parents_main__
而不是__main__
。这就是为什么在验证__name__
变量时,您的流程不会循环。
有关详细信息,请查看章节Safe importing of main module