windows的python多进程

windows的python多进程

  • 问题
  • 原因
  • 扩展

问题

from multiprocessing import Process


def func():
    print("joshua")


p = Process(target=func)
p.start()
p.join()

运行结果:

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 创建子进程时,子进程会导入当前文件,导致一直递归生成子进程。

扩展

因为子进程是通过导入当前文件,拷贝父进程的属性,所以父进程中在main方法中定义的全局变量,无法拷贝到子进程中

from multiprocessing import Process


def func():
    print(name)


if __name__ == '__main__':
    name = "joshua"
    func()
    p = Process(target=func)
    p.start()
    p.join()

运行结果:

joshua
Process Process-1:
	...
NameError: name 'name' is not defined

你可能感兴趣的:(#,PythonError,python)