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

问题描述 投票:0回答: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 子句有何不同?

python python-3.x multiprocessing
3个回答
6
投票

这是 MS Windows 上

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


2
投票

子流程具有以下

__name__
__parents_main__
,不再是
__main__
。这就是为什么当您测试
__name__
变量时,您的进程不会循环。

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


0
投票
def f(x, a):
    return a*x*x

def foo():
    if __name__ == "__main__":
        from multiprocessing import Pool
        import functools
        with Pool(4) as p:
            print(p.map(functools.partial(f, a=1.0), range(1,50)))

foo()

© www.soinside.com 2019 - 2024. All rights reserved.