pytorch的坑-An attempt has been made to start a new process before the current process has finished its bootstrapping phase.

报错:
RuntimeError:
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:

        if __name__ == '__main__':
            freeze_support()
            ...

    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable.

这个错误通常发生在使用 Python 的 multiprocessing 模块时,尤其是在 Windows 操作系统上。错误消息指出,在当前进程完成其引导阶段之前,尝试启动一个新进程。这通常是因为没有正确地使用 if name == 'main': 来保护启动多进程的代码块。

在 Windows 上,由于缺少类似于 Unix/Linux 中的 fork() 系统调用,Python 使用 spawn 来创建新进程。这意味着在启动一个新进程时,Python 需要导入主模块来再次执行它。如果代码直接创建进程而没有适当的保护,它可能会导致无限递归地创建进程,或者在这种情况下,尝试在进程完全初始化之前启动新进程。

要解决这个问题,请确保你的多进程启动代码位于 if name == 'main': 块中。这样,当模块被导入时,这部分代码不会被执行,只有在直接运行此脚本时才执行。例如:

from multiprocessing import freeze_support  
  
def main():  
    # 你的多进程代码  
    pass  
  
if __name__ == '__main__':  
    freeze_support()  # 如果计划将程序打包成可执行文件,这行是必须的  
    main()
posted @ 2024-07-06 00:45  JaxonYe  阅读(55)  评论(0编辑  收藏  举报