Windows multiprocessing

后端 未结 1 1192
天涯浪人
天涯浪人 2021-01-23 05:52

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

The pydoc states you should protect the entry point of a

相关标签:
1条回答
  • 2021-01-23 06:33

    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__':
        ...
    

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

    python mymodule.py
    

    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.

    0 讨论(0)
提交回复
热议问题