2871

14 分钟

#Python 的进程间通信

进程的内存空间和资源是独立的,尝试通过全局变量传递信息会发现无法实现。

例如下面代码,子进程会打印空字符串而不是 Ciallo~(∠・ω< )⌒★

from multiprocessing import Process message:str = '' def worker(): print(message) if __name__ == '__main__': message = 'Ciallo~(∠・ω< )⌒★' # 尝试发送信息 p = Process(target=worker) # 创建进程 p.start() # 启动进程 p.join() # 等待进程结束

在 Python 中可以使用 队列(Queue)管道(Pipe) 进行进程间通信(IPC)。

#队列

通过 multiprocessing 模块的 Queue 类创建队列,通过 put 方法向队列尾部添加数据,通过 get 方法从队列头部取出数据。

QueueTopology queue Head A B C D Tail get() get() queue:f0->get() put() put() put()->queue:f5

示例:

from multiprocessing import Process, Queue # 生产者,发送数据 def producer(q:Queue): for i in range(5): q.put(i) # 发送数据 q.put(None) # 发送 None 来表示结束 # 消费者,接收数据 def consumer(q:Queue): while (item := q.get()) is not None: print(f'收到了 {item}') if __name__ == '__main__': q = Queue() # 创建队列 p1 = Process(target=producer, args=(q,)) # 创建进程 p2 = Process(target=consumer, args=(q,)) p1.start() # 启动进程 p2.start() p1.join() # 等待进程退出 p2.join()

运行结果:

收到了 0 收到了 1 收到了 2 收到了 3 收到了 4

#管道

通过 multiprocessing 模块的 Pipe 函数创建管道,它会返回管道的两个端点,从任意一端写入时另一端可以读取。

PipeStructure end1 端点1 buffer 缓冲区 end1->buffer send() buffer->end1 recv() end2 端点2 buffer->end2 recv() end2->buffer send()

示例:

from multiprocessing import Process, Pipe from multiprocessing.connection import PipeConnection # 生产者,发送数据 def producer(tx:PipeConnection): for i in range(5): tx.send(i) # 发送数据 tx.send(None) # 发送 None 来表示结束 # 消费者,接收数据 def consumer(rx:PipeConnection): while (item := rx.recv()) is not None: print(f'收到了 {item}') if __name__ == '__main__': tx, rx = Pipe() # 创建管道 p1 = Process(target=producer, args=(tx,)) # 创建进程 p2 = Process(target=consumer, args=(rx,)) p1.start() # 启动进程 p2.start() p1.join() # 等待进程退出 p2.join()

运行结果:

收到了 0 收到了 1 收到了 2 收到了 3 收到了 4

创建于 2025/5/11

更新于 2025/5/21