Python 在一个简单的示例中,说明“多处理”的额外好处

Python 在一个简单的示例中,说明“多处理”的额外好处,python,multiprocessing,Python,Multiprocessing,我正在从“介绍Python”学习多处理,有这样一个例子来演示多处理 import os import multiprocessing as mp def do_this(what): whoami(what) def whoami(what): print(f"Process {os.getpid()} says: {what}.") if __name__ == "__main__": whoami("I'm the main program.") for

我正在从“介绍Python”学习
多处理
,有这样一个例子来演示
多处理

import os
import multiprocessing as mp

def do_this(what):
    whoami(what)

def whoami(what):
    print(f"Process {os.getpid()} says: {what}.")

if __name__ == "__main__":
    whoami("I'm the main program.")
    for i in range(4):
        p = mp.Process(target=do_this, args=(f"I'm function {i}",))
        p.start()

def do_this(what):
    whoami(what)

def whoami(what):
    print(f"Process {os.getpid()} says: {what}.")

if __name__ == "__main__":
    whoami("I'm the main program.")
    for i in range(4):
        do_this(f"I'm function {i}")
运行它并通过:

## -- End pasted text --
Process 2197 says: I'm the main program..
Process 2294 says: I'm function 1.
Process 2293 says: I'm function 0.
Process 2295 says: I'm function 2.
Process 2296 says: I'm function 3.
但是,它很容易通过单个过程实现:

def do_this(what):
    whoami(what)

def whoami(what):
    print(f"Process {os.getpid()} says: {what}.")

if __name__ == "__main__":
    whoami("I'm the main program.")
    for i in range(4):
        do_this(f"I'm function {i}")
## -- End pasted text --
Process 2197 says: I'm the main program..
Process 2197 says: I'm function 0.
Process 2197 says: I'm function 1.
Process 2197 says: I'm function 2.
Process 2197 says: I'm function 3.
我尽量掌握
多处理的思想,如果不引入,它解决了什么问题

在上面的例子中,
多处理的额外好处是什么?

背后的想法是,您可以处理一个需要大量数学运算的问题,并在多个计算系统之间分配工作负载

import os
import multiprocessing as mp

def do_this(what):
    whoami(what)

def whoami(what):
    print(f"Process {os.getpid()} says: {what}.")

if __name__ == "__main__":
    whoami("I'm the main program.")
    for i in range(4):
        p = mp.Process(target=do_this, args=(f"I'm function {i}",))
        p.start()

def do_this(what):
    whoami(what)

def whoami(what):
    print(f"Process {os.getpid()} says: {what}.")

if __name__ == "__main__":
    whoami("I'm the main program.")
    for i in range(4):
        do_this(f"I'm function {i}")
这通常在一台计算机内完成,但也可以通过计算机网络完成。在python中,“多进程”是在一台计算机中执行的

这种工作方式是现代cpu有几个核心。每个内核就像它自己的处理器,一次可以处理一个线程

cpu被划分为多个核的原因是,很难使单个核更快,但很容易添加更多的核,这反过来又会提高总体处理能力

问题是每个内核一次只能执行一个线程。所以,如果你的程序完全是单线程的,那么不管你有多少个内核,它都只会以单内核的速度运行

像上面那样分割python脚本,将其分割为几个线程,这些线程可以在不同的内核上独立运行。每个核心处理您给它的任务,最终答案被合并并打印到屏幕上


在您的示例中,使用多处理真的没有什么好处,因为您没有做大量的工作来降低程序的速度,但是假设您有大量的数组,需要昂贵的数学运算才能运行,将该数组划分为多个部分并将这些部分分配给不同的进程将使整个程序运行得更快。

需要注意的几件事:一般来说,多处理不仅在一台计算机上,而且可以跨多台计算机(也称为“集群”),但Python的
多处理
模块仅在一台计算机上运行。Python还有不同于操作系统线程的
线程。多个Python
线程实际上在一个操作系统级线程上运行。Python的
多处理
模块使用单独的进程来允许使用多个内核,但它们不能像一个进程的多个线程那样共享内存,这是一种简化。@sudo谢谢,要点非常好。我编辑了我的答案以反映你写的内容。