Windows多处理 [英] Windows multiprocessing

查看:103
本文介绍了Windows多处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我发现Windows在进行多处理时有点费劲,对此我有疑问.

As I have discovered windows is a bit of a pig when it comes to multiprocessing and I have a questions about it.

pydoc指出您应该使用多重处理时保护Windows应用程序的入口点.

The pydoc states you should protect the entry point of a windows application when using multiprocessing.

这是否仅意味着创建新流程的代码?

Does this mean only the code which creates the new process?

例如

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()

在此脚本中,您需要将其包装在 main 中,因为产生该过程的行. 但是如果有的话怎么办?

In this script you need to wrap this in if main because the line in spawning the process. But what about if you had?

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中有一个__main__,会发生什么情况?如果正在创建进程,该代码中的代码会被执行吗?

注意:我知道代码将无法编译.这只是一个例子.

推荐答案

pydoc声明您在使用多处理程序时应保护Windows应用程序的入口点.

The pydoc states you should protect the entry point of a windows application when using multiprocessing.

我的理解有所不同:说明文件

My interpretation differs: the documentations states

主模块可以由新的Python解释器安全地导入,而不会引起意外的副作用(例如,启动新进程).

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)不应创建新进程.也就是说,您可以通过使用

So importing your module (import mymodule) should not create new processes. That is, you can avoid starting processes by protecting your process-creating code with an

if __name__ == '__main__':
    ...

因为...中的代码仅在您的程序作为主程序运行时运行,也就是说,当您运行时

because the code in the ... will only run when your program is run as main program, that is, when you do

python mymodule.py

或将其作为可执行文件运行时,而不是import文件时.

or when you run it as an executable, but not when you import the file.

因此,要回答有关file2的问题:不,您不需要保护,因为在import file2期间未启动任何进程.

So, to answer your question about the file2: no, you do not need protection because no process is started during the import file2.

此外,如果将if __name__ == '__main__'放在file2.py中,则由于导入了file2而不会作为主程序执行,因此它不会运行.

Also, if you put an if __name__ == '__main__' in file2.py, it would not run because file2 is imported, not executed as main program.

编辑:此处是不执行此操作会发生什么情况的示例保护您的流程创建代码:它可能会循环并创建大量流程.

edit: here is an example of what can happen when you do not protect your process-creating code: it might just loop and create a ton of processes.

这篇关于Windows多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆