Windows多处理

Mat*_*our 2 python windows multiprocessing

正如我所发现的,在进行多处理时,windows有点麻烦,对此我有一个疑问。

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

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

例如

脚本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()
Run Code Online (Sandbox Code Playgroud)

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

剧本2

file1.py

import file2
if __name__ == '__main__':
    p = Aclass().start()
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

在这种情况下需要保护什么? 如果在文件2中有一个if __main__会发生什么,如果正在创建一个进程,该代码中的代码会被执行吗?

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

ber*_*lus 5

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

My interpretation differs: the documentations states

the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process).

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__':
    ...
Run Code Online (Sandbox Code Playgroud)

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

python mymodule.py
Run Code Online (Sandbox Code Playgroud)

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

So, to answer your question about the file2: no, you do not need protection because no process is started during the import 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.