没有“if __name__ =='__ main__'的python3.x多处理循环:”

时间:2012-07-16 09:01:23

标签: python python-3.x multiprocessing

我有这个文件(它没有做任何有用的工作,只是为了学习):

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子句有什么不同?

2 个答案:

答案 0 :(得分:5)

这是MS Windows上multiprocessing的问题:主要模块由子任务导入,因此任何不受if __name__ . . .子句保护的代码都会再次运行,从而导致无限循环。

答案 1 :(得分:2)

子流程具有以下__name____parents_main__而不是__main__。这就是为什么在验证__name__变量时,您的流程不会循环。

有关详细信息,请查看章节Safe importing of main module