Python 的多进程模块 multiprocessing
提供了一种创建并行执行程序的方法。使用多进程可以在多核心的 CPU 上实现真正的并行计算。
基本概念
多进程与多线程的区别在于,多线程在同一时刻只能在一个核心上运行,而多进程可以在多个核心上同时运行。
使用方法
创建进程
from multiprocessing import Process
def worker():
print("Hello from worker!")
if __name__ == "__main__":
p = Process(target=worker)
p.start()
p.join()
进程间通信
进程间通信可以通过多种方式实现,例如 Queue
、Pipe
等。
from multiprocessing import Process, Queue
def worker(q):
q.put([42, None, 'hello'])
if __name__ == "__main__":
q = Queue()
p = Process(target=worker, args=(q,))
p.start()
print(q.get()) # 输出: [42, None, 'hello']
p.join()
管道 (Pipe)
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == "__main__":
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print(parent_conn.recv()) # 输出: [42, None, 'hello']
p.join()
进程池 (Pool)
进程池允许你创建一组进程,然后分配任务给它们。
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == "__main__":
with Pool(5) as p:
print(p.map(f, [1, 2, 3, 4, 5]))
更多关于 Python 多进程的内容,可以参考本站的 Python 多进程教程。
图片示例
Python Multiprocessing