Why does this multiprocessing code fail?

This question already has an answer here:

  • Why does Python's multiprocessing module import __main__ when starting a new process on Windows? 1 answer

  • When you create a new child process, the child process might (mostly depending on the OS you are using) re-import the current module.

    In your case, re-importing the module also executes these two lines:

    Process(target=sample).start()
    Process(target=sample).start()
    

    and what happens is, what the error message tells you:

    An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module

    While setting up the proper environment for your first child process, the code tries to fork off another child process. The manager detects this and tells you that this is not okay.

    if __name__ == '__main__':
        Process(target=sample).start()
        Process(target=sample).start()
    

    is a guard condition that allows the current module to be imported in the child module without this problem, because only the --well-- main module's name is __main__ .

    链接地址: http://www.djcxy.com/p/54794.html

    上一篇: Python中的import关键字如何工作?

    下一篇: 为什么这个多处理代码失败?