[英]Why does Python's multiprocessing module import __main__ when starting a new process on Windows?
I am playing around with a library for my beginner students, and I'm using the multiprocessing module in Python. 我正在为初学者准备一个图书馆,并且正在使用Python中的多处理模块。 I ran into this problem: importing and using a module that uses multiprocessing without causing infinite loop on Windows
我遇到了这个问题: 导入并使用使用多处理的模块,而不会在Windows上引起无限循环
As an example, suppose I have a module mylibrary.py
: 例如,假设我有一个模块
mylibrary.py
:
# mylibrary.py
from multiprocessing import Process
class MyProcess(Process):
def run(self):
print "Hello from the new process"
def foo():
p = MyProcess()
p.start()
And a main program that calls this library: 还有一个调用该库的主程序:
# main.py
import mylibrary
mylibrary.foo()
If I run main.py
on Windows, it tries to import main.py into the new process, meaning the code is executed again which results in an infinite loop of process generation. 如果我在Windows上运行
main.py
,它将尝试将main.py导入新进程,这意味着将再次执行代码,这将导致进程生成的无限循环。 I can fix it like so: 我可以这样修复它:
import mylibrary
if __name__ == "__main__":
mylibrary.foo()
But, this is pretty confusing for beginners, and moreover it seems like it shouldn't be necessary. 但是,这对于初学者来说非常令人困惑,而且似乎没有必要。 The new process is being created in
mylibrary
, so why doesn't the new process just import mylibrary
? 正在创建的新进程
mylibrary
,那么为什么不新工艺只需要导入mylibrary
? Is there a way to work around this issue without having to change main.py
? 有没有一种方法可以解决此问题而不必更改
main.py
?
I am using Python 2.7, by the way. 顺便说一下,我正在使用Python 2.7。
Windows doesn't have fork
, so there's no way to make a new process just like the existing one. Windows没有
fork
,因此没有办法像现有的那样进行新的处理。 So the child process has to run your code again, but now you need a way to distinguish between the parent process and the child process, and __main__
is it. 因此,子进程必须再次运行您的代码,但是现在您需要一种区分父进程和子进程的方法,而
__main__
是。
This is covered in the docs here: http://docs.python.org/2/library/multiprocessing.html#windows 此处的文档中对此进行了介绍: http : //docs.python.org/2/library/multiprocessing.html#windows
I don't know of another way to structure the code to avoid the fork bomb effect. 我不知道另一种结构化代码的方式来避免前叉炸弹效应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.