""" 总结: 进程之间的通信可以通过Queue或者Pipe来完成 Pipe是一种双向通信机制,有两个端口,可以在两个进程之间进行双向通信。这意味着当一个进程发送消息时,必须等待另一个进程在管道中读取消息后才能继续。 Queue则只是一种单向通信机制,即只能由生产者向队列发送数据,由消费者从队列接收数据,不要求两个进程同步等待对方的响应。 Pipe的实现方式使用了底层的OS级别的IPC(Inter-Process Communication)机制,即管道,因此Pipe的速度比Queue稍快。 而Queue的实现则使用pickle模块将数据临时序列化为二进制数据,将其发送到队列中,然后由接收方进程将其反序列化为相应的Python对象。 如果您要处理相对较小的数据量,则速度方面的差异可能不太明显,但如果数据量较大则应考虑Pipe Pipe示例:
from multiprocessing import Process, Pipe
def say_hello(conn):
conn.send('Hello')
msg = conn.recv()
print(f'Received the message: {msg}')
def say_hi(conn):
msg = conn.recv()
print(f'Received the message: {msg}')
conn.send('Hi')
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p1 = Process(target=say_hello, args=(parent_conn,))
p2 = Process(target=say_hi, args=(child_conn,))
p1.start()
p2.start()
p1.join()
p2.join()
Queue示例:
import time
from multiprocessing import Process, Queue, JoinableQueue
import multiprocessing
def down(q: Queue):
image = ['hello.py', 'boy.py', 'man.py']
for i in image:
print('正在下载{}'.format(i))
# 将文件存入Queue
q.put(i)
time.sleep(0.2)
# 发送一个 None 用于停止 getfil 进程
q.put(None)
def getfil(q: Queue):
while True:
item = q.get()
if item is None:
# 发现 None,表明已经没有待处理项了
q.task_done() # 主动告诉 Queue 完成了任务
print('保存完了')
break
else:
time.sleep(0.2)
print(f'文件保存成功{item}')
q.task_done()
if __name__ == '__main__':
# JoinableQueue 是 Queue 的一个子类,它专门用于让生产者在向队列中添加项目后,能够知道消费者何时已经处理完这些项目
q = JoinableQueue(5)
p2 = Process(target=getfil, args=(q,))
p2.start()
p1 = Process(target=down, args=(q,))
p1.start()
p1.join()
# 等到所有的任务完成
q.join()
print('保存完毕')
"""