报错:
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.
原因:
这个错误通常发生在 Windows 平台上,当使用 multiprocessing 模块创建新进程时,由于操作系统的限制,需要使用 if __name__ == '__main__': 以及 freeze_support() 函数来避免出现错误。 freeze_support() 函数是为了在 PyInstaller 打包应用程序时解决 Windows 平台上的多进程问题而设计的,它会在 Windows 平台上启动进程时执行一个特殊的“冻结”模块(frozen module)来解决多进程问题。如果你的程序没有被打包成可执行文件,可以省略 freeze_support() 函数。 正确的写法应该是:
import multiprocessing
def worker():
print('worker')
if __name__ == '__main__':
multiprocessing.freeze_support() # 可以省略
p = multiprocessing.Process(target=worker)
p.start()
p.join()
在这个例子中,我们首先检查当前模块是否是主模块(即被直接执行的模块),如果是,则调用 freeze_support() 函数来解决多进程问题。然后创建一个新进程来运行 worker() 函数,并等待其结束。