python - 最小演示示例中 `multiprocessing` 的额外好处

标签 python multiprocessing

我正在学习《Python简介》中的multiprocessing,有这样一个例子来演示multiprocessing

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.

我尽力掌握多处理的想法,以及如果不引入它会解决什么问题。

在上述情况下,多处理有什么额外好处

最佳答案

背后的想法multiprocessing是您可以解决需要大量数学运算才能运行的问题,并在多个计算系统之间分配工作负载。

这通常在单台计算机内完成,但也可以通过计算机网络进行。对于 python,“多进程”在一台计算机内执行。

其工作原理是现代 CPU 有多个核心。每个核心就像它自己的处理器,因为它一次可以处理一个线程。

CPU 被划分为多个核心的原因是,很难让单个核心变得更快,但添加更多核心却很容易,从而提高总处理能力。

这样做的问题是每个核心一次只能执行一个线程。因此,如果您的程序完全是单线程的,那么无论您有多少个核心,它都只会以其所在的单核心的速度运行。

像上面那样划分你的 python 脚本,将其分成几个可以在不同内核上独立运行的线程。每个核心都会处理您赋予它的任务,并将最终答案组合起来并打印到屏幕上。

在你的例子中,使用多处理确实没有什么好处,因为你没有做大量的工作来减慢程序的速度,但是假设你有大量的数组,需要昂贵的数学来运行,将该数组分成几个部分并将这些部分分配给不同的进程将使整个程序运行得更快。

关于python - 最小演示示例中 `multiprocessing` 的额外好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50635378/

相关文章:

python - 为什么我不能在 multiprocessing.Pool 中使用 operator.itemgetter?

python - 如何在 xlsxwriter 中对整列使用色阶

python - Postgres SSL SYSCALL 错误 : EOF detected with python and psycopg

python - 如何在 PyQt4 进程中使用多核 python?

python - 使用 Python 生成多个进程

python - 多处理提前退出

python - Plotly:如何设置 x 轴上时间序列的主要刻度线/网格线的值?

java - 测量 Google App Engine 中的任务队列成本

python - 如何链接在 for 循环中创建的 python tkinter 小部件?

类中的 Python 3 multiprocessing.Process?