3

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

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

4

2 回答 2

5

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

于 2012-07-16T09:50:25.250 回答
2

子流程具有以下内容__name____parents_main__并且不再__main__具有。__name__这就是为什么在测试变量时您的过程不会循环的原因。

有关这方面的更多信息,请参阅安全导入主模块一章

于 2012-07-16T09:34:36.597 回答