Depending on the platform, [multiprocessing](https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing) supports three ways to start a process. These start methods are

  • fork,【“拷贝”几乎所有资源】【支持文件对象/线程锁等传参】【unix】【任意位置开始】【速度快】windows不支持fork
    The parent process uses [os.fork()](https://docs.python.org/3/library/os.html#os.fork) to fork the Python interpreter. The child process, when it begins, is effectively identical to the parent process. All resources of the parent are inherited by the child process. Note that safely forking a multithreaded process is problematic.Available on Unix only. The default on Unix.

  • spawn,【run参数传必备资源】【不支持文件对象/线程锁等传参】【unix、win】【main代码块开始】【速度慢】
    The parent process starts a fresh python interpreter process. The child process will only inherit those resources necessary to run the process object’s [run()](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Process.run) method. In particular, unnecessary file descriptors and handles from the parent process will not be inherited. Starting a process using this method is rather slow compared to using fork or forkserver.Available on Unix and Windows. The default on Windows and macOS.

  • forkserver,【run参数传必备资源】【不支持文件对象/线程锁等传参】【部分unix】【main代码块开始】
    When the program starts and selects the forkserver start method, a server process is started. From then on, whenever a new process is needed, the parent process connects to the server and requests that it fork a new process. The fork server process is single threaded so it is safe for it to use [os.fork()](https://docs.python.org/3/library/os.html#os.fork). No unnecessary resources are inherited.Available on Unix platforms which support passing file descriptors over Unix pipes.

1.基于fork拷贝模式中的操作:

主进程中的数据会拷贝进入子进程,所以子进程中的数据可以使用主进程的数据
但是子进程无法修改主进程中的数据

  1. import multiprocessing
  2. import time
  3. """
  4. def task():
  5. print(name)
  6. name.append(123)
  7. if __name__ == '__main__':
  8. multiprocessing.set_start_method("fork") # fork、spawn、forkserver
  9. name = []
  10. p1 = multiprocessing.Process(target=task)
  11. p1.start()
  12. time.sleep(2)
  13. print(name) # []
  14. """

2.spawn模式只传递参数,不拷贝数据

spawn是windows采用的模式,只传参,不拷贝,如果想传递拷贝数据的话
需要通过传参的形式,把数据放入其中
注意
1.即使通过传参,把数据传入,也是只拷贝,不改变原先数据的值
2.spawn 模式 传递参数时,不能传入文件对象和线程锁
3.spawn模式必须位于main函数下执行

  1. import multiprocessing
  2. import time
  3. def task(name):
  4. print(name)
  5. name.append(123)
  6. if __name__ == '__main__':
  7. multiprocessing.set_start_method("spawn") # fork、spawn、forkserver
  8. name = []
  9. p1 = multiprocessing.Process(target=task,agrs=(name,))
  10. p1.start()
  11. time.sleep(2)
  12. print(name) # []