unix的多进程和windows多进程区别

UniX:

用fork(分支---原生的完全并行的), 子进程从地址空间直接获得数据及python的运行配置

windows:

用spawn(产生----催生的), 另外同时并列启动多个python解释器,会分别执行被多进程策略分配的任务,同时也都会导入主进程的实现模块到自己的上下文中

所以要想兼容windows:

  1. 将多进程的实现代码放在if name=="main":下包裹. 否则当主进程模块被导入子进程上下文中时 又会直接运行主进程的进程产生策略部分,导致在一个子进程的引导环境中同时执行了下一个子进程的开启,会报错)

  2. 确保其他 "自定义的函数" collate_fn, worker_init_fn or dataset代码要 放在main外面(全局变量) , 确保其他进程都能访问获得.(函数序列化后是指针索引,而不是二进制码)

from multiprocessing import Process
def foo():
    print("hello")


p= Process(target=foo)
p.start()
"""
RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.
"""

from multiprocessing import Process
def foo():
    print("hello")

if __name__ == "__main__":
    p= Process(target=foo)
    p.start()
# hello
原文地址:https://www.cnblogs.com/Henry-ZHAO/p/13960121.html