Python3关于多进程和if name == “main“的问题
代码如下:
#coding:'utf-8'
import multiprocessing
import os
def pro():
print('子进程', os.getpid())
# if __name__ == '__main__':
p1 = multiprocessing.Process(target=pro)
p1.start()
运行出错:
…
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if name == ‘main‘:
freeze_support()
…
The “freeze_support()” line can be omitted if the program
is not going to be frozen to produce an executable.
…
原因
这是 Windows 上多进程的实现问题。在 Windows 上,子进程会自动 import 启动它的这个文件,而在 import 的时候是会执行这些语句的。如果你这么写的话就会无限递归创建子进程报错。但是在multiprocessing.Process的源码中是对子进程再次产生子进程是做了限制的,是不允许的,于是出现如上的错误提示。所以必须把创建子进程的部分用那个 if 判断保护起来,import 的时候 name 不是 main ,就不会递归运行了。
本文探讨了Python在Windows环境下使用多进程时遇到的一个常见问题:尝试在引导阶段前启动新进程导致的错误。文章详细解释了错误产生的原因,并给出了正确的解决办法。
2177





