因为我发现在多处理方面 Windows 有点笨拙,我对此有疑问。
pydoc 说明你应该 protect the entry point of a windows application when using multiprocessing .
这是否意味着只有创建新进程的代码?
例如
脚本 1
import multiprocessing
def somemethod():
while True:
print 'do stuff'
# this will need protecting
p = multiprocessing.Process(target=somemethod).start()
# this wont
if __name__ == '__main__':
p = multiprocessing.Process(target=somemethod).start()
在这个脚本中,你需要将其包装在 if main 中,因为生成进程的那一行。 但如果你有呢?
脚本2
file1.py
import file2
if __name__ == '__main__':
p = Aclass().start()
file2.py
import multiprocessing
ITEM = 0
def method1():
print 'method1'
method1()
class Aclass(multiprocessing.Process):
def __init__(self):
print 'Aclass'
super(Aclass, self).__init__()
def run(self):
print 'stuff'
在这种情况下需要保护什么? 如果文件 2 中有一个 if __main__ 会发生什么,如果正在创建一个进程,里面的代码会被执行吗?
注意:我知道代码不会编译。这只是一个例子。
最佳答案
The pydoc states you should protect the entry point of a windows application when using multiprocessing.
我的解释不同:文档说明
the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).
因此导入您的模块(import mymodule
)不应创建新进程。也就是说,您可以通过使用
if __name__ == '__main__':
...
因为...中的代码只会在您的程序作为主程序运行时运行,也就是说,当您这样做时
python mymodule.py
或者当您将它作为可执行文件运行时,而不是当您导入
文件时。
因此,回答您关于 file2
的问题:不,您不需要保护,因为在 import file2
期间没有启动任何进程。
此外,如果您在 file2.py
中放置一个 if __name__ == '__main__'
,它不会运行,因为 file2
是导入的, 不作为主程序执行。
编辑: here是一个示例,说明当您不保护创建进程的代码时会发生什么:它可能只是循环并创建大量进程。
关于python - Windows 多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802211/