关于python:为什么这个多处理代码会失败?

Why does this multiprocessing code fail?

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
def sample():
    pass

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

上述代码失败,出现错误:

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

但这段代码运行良好:

1
2
3
4
5
def sample():
    pass
if __name__ == '__main__':
    Process(target=sample).start()
    Process(target=sample).start()

在这种情况下,为什么主模块会影响我的代码执行?我无法正确理解错误消息。

注:如果uuu name_uuu=="uuu main_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu但无法理解它与我的代码的相关性。


当您创建新的子进程时,子进程可能(主要取决于您使用的操作系统)重新导入当前模块。

在您的情况下,重新导入模块还执行以下两行:

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

发生的是,错误消息告诉您:

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

在为第一个子进程设置适当的环境时,代码试图派生出另一个子进程。经理检测到这个,并告诉你这不好。

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

是一种保护条件,允许在子模块中导入当前模块而不会出现此问题,因为只有--well-主模块的名称是__main__